开发者

Multiple IN() checks on joined table with mysql 5.1

开发者 https://www.devze.com 2023-02-26 17:52 出处:网络
I have a table with user data and a m:n relationship table for the assignment to different groups. To filter all the Users which belong to group 1 and 2 I wrote the following SQL:

I have a table with user data and a m:n relationship table for the assignment to different groups. To filter all the Users which belong to group 1 and 2 I wrote the following SQL:

SELECT * 
FROM user AS u
LEFT JOIN user_groups AS g ON g.uid = u.uid
WHERE 1 IN (g.gid) AND 2 IN (g.gid)

Unfortunately this statement does not work. The result is empty, but there are users wich are in both groups. When I make a second join to user_groups it works:

SELECT * 
FROM user AS u
LEFT JOIN user_groups AS g ON g.uid = u.uid
LEFT JOIN user_groups AS g2 ON g2.uid = u.uid
WHERE 1 IN (g.gid) AND 2 IN (g2.gid)

Can anybody explain to m开发者_如何学JAVAe, what is wrong with the first statement? It wold be great if anybody could show me, how to solve this problem with one join, because I have to check a various amount of groups.

Thank you in advance, Pete


In your first query try replacing AND with OR. The column gid cant be both 1 and 2 at the same time.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号