2009-01-05 36 views
0

大家好是有可能重寫查詢:重寫子查詢(不)作爲加入

select userid from User where userid not in(select userid from UserRole where roleid in(8));

的加入?

問題是,一個用戶可能有幾個角色
謝謝你提前。

 
mysql> desc User; 
+--------------------+-------------------+------+-----+---------+----------------+ 
| Field    | Type    | Null | Key | Default | Extra   | 
+--------------------+-------------------+------+-----+---------+----------------+ 
| userId    | int(11)   | NO | PRI | NULL | auto_increment | 
| userName   | varchar(50)  | YES |  | NULL |    | 

...等用戶相關的列

 
mysql> desc UserRole; 
+--------+---------+------+-----+---------+-------+ 
| Field | Type | Null | Key | Default | Extra | 
+--------+---------+------+-----+---------+-------+ 
| userId | int(11) | NO | PRI | 0  |  | 
| roleId | int(11) | NO | PRI | 0  |  | 
+--------+---------+------+-----+---------+-------+ 
+0

我聞到作業... – cletus 2009-01-05 11:22:38

回答

0

也許這是否行得通呢?

select userid from User 
left outer join 
(select userid, roleid from UserRole where roleid in(8)) v 
on User.userid = v.userid 
where roleid is null; 
+0

OP想重寫子查詢作爲連接,但是這個查詢仍然有子查詢。 – Raptor 2012-11-08 02:37:18

+1

@ShivanRaptor:(a)OP沒有指定任何子查詢只是「我可以重寫爲連接」; (b)OP已經接受了我的回答,所以大概對此感到滿意; (c)這一切都發生在近4年前! ;-) – 2012-11-08 10:52:50

0

我想這應該讓你每個人如果你想要去的可讀性,你可以使用EXCEPT子句誰比8

select userid from User 
where not exists 
    (select UserId from UserRole 
    where UserRole.userid = User.userid and roleid not in(8)) 
0

其他角色。

I.e.

select userId from user 
except 
select userId from UserRole where roleId <> 8 

不知道MySQL是否支持「Except」。

+0

注意:MySQL不支持`EXCEPT` – Raptor 2012-11-08 02:35:00

1

我沒有測試過這個,但我認爲它的工作原理。

select userID from user 
left join UserRole 
on user.userID = UserRole.userID 
and UserRole.roleID = 8 
where UserRole.roleID IS NULL