2017-06-29 93 views
1

我有用戶和組之間的關係。用戶可以在一個組中或不在。子查詢優化

編輯:在模型中添加了一些東西,使其更方便。

enter image description here

比方說,我有一個規則的組中添加用戶認爲它有特定的小鎮,像18歲的自定義元數據)。

Curently,我這樣做,知道我要組住在巴黎18區誰是人的補充哪些用戶:

 SELECT user.id AS 'id' 
     FROM user 
     LEFT JOIN 
     (
      SELECT user_id 
      FROM user_has_role_group 
      WHERE role_group_id = 1 -- Group for Paris 
     ) 
     AS T1 
     ON user.id = T1.user_id 
     WHERE 
     (
     user.town = 'Paris' AND JSON_EXTRACT('custom_metadata', '$.age') = 18 
     ) 
     AND T1.user_id IS NULL 

它的工作原理&給我的用戶插入的ID組。

但是,當我有50個組進行時,比如50個城鎮或不同年齡段,它迫使我做50個請求,這對我的數據庫來說非常緩慢並且效率不高。

我怎樣才能爲每個組生成結果?

喜歡的東西:

role_group_id   user_to_add 
1     1 
1     2 
2     1 
2     3 

我知道只有這樣,才能做到這一點,現在是做類似上面的幾個子查詢的UNION,當然這是非常緩慢的。

請注意,custom_metadata字段是用戶定義的字段。我無法創建特定的列或表格。

非常感謝您的幫助。

+0

請注意,該組是一個保留字,對於表/列標識符來說它是一個糟糕的選擇 - 即使在任意示例中也是如此。 – Strawberry

+0

你怎樣設法創建'user_has_group'行,其中'group_id'已設置,但'user_id'未設置? – RiggsFolly

+0

我也在努力去理解什麼使用一個'Group'表只有一個'id',並且沒有其他的表示這個組像什麼'name' – RiggsFolly

回答

1

,如果我好明白你:

select user.id, grp.id 
from user, role_group grp 
where (user.id, grp.id) not in (select user_id, role_group_id from user_has_role_group) and user.town in ('Paris', 'Warsav') 

用戶和組,他們不是從城鎮之一屬於的那個代碼給予名單..

+0

其實,我認爲這可以奏效!隨着一些調整。 – switch

0

添加缺少的條目user_has_role_group,你可能想在這些城鎮名稱和他們的group_id之間有一些映射。

下面的例子只是使用一個子查詢和聯合。
但是,您可以用表中的選擇替換它。
甚至可能來自role_group,如果這些名稱與用戶城鎮名稱相關。

insert into user_has_role_group (user_id, group_id) 
select u.user_id, g.group_id 
from user u 
join (
    select 'Paris' as name, 1 as group_id union all 
    select 'Rome', 2 
    -- add more towns here 
) g on (u.town = g.name) 
left join user_has_role_group ug 
    on (ug.user_id = u.user_id and ug.role_group_id = g.group_id) 
where u.town in ('Paris','Rome') -- add more towns here 
    and json_extract(u.custom_metadata, '$.age') = 18 
    and ug.id is null;