2017-02-09 78 views
1

在表格內有2列:useridroleid。每個用戶應至少有roleid 4。目前大約有10.000條記錄,但不知何故少量用戶不具備此角色。如果它不存在於MySQL表中,則添加一行

視覺例如:

userid | roleid 
1   1 
1   4 
2   1 
2   4 
3   1 <---------- userid 3 misses roleid 4! 
4   1 
4   4 

是否有可能執行查詢,並添加與用戶ID和角色ID行時該組合不存在?

回答

4

是的。

insert into userRoles(userid, roleid) 
    select userid, 4 
    from userRoles 
    group by userid 
    having sum(roleid = 4) = 0; 

having子句中的sum(role = 4)計算行對於具有4每個用戶的數量。 = 0說沒有。

注意:這爲該表中的所有用戶提供了角色ID 4.可能有用戶根本沒有任何角色。

如果你想他們,然後用users表:

insert into userRoles(userid, roleid) 
    select u.userid, 4 
    from users u 
    where not exists (select 1 from userRoles ur where ur.userid = u.userid); 
0

您要搜索的用戶有沒有角色ID

insert into yourTable (userId, roledid) 
select userid, 4 
from yourTable 
where roleid <>4 
4
相關問題