开发者

Help with SQL statement (Select users who have product A, but NOT product B, C or D)

Table 1: users Fields: id, email, first_name

Table 2: resources Fields: user_id, product_id

I want to select emai开发者_JAVA百科l, first_name from users table where the user has product_id 22 BUT NOT product ID 1, 3 or 35

What's the SQL to pull this list?


select email, first_name 
from users
where id in (select user_id from resources where product_id=22)
and id not in (select user_id from resources where product_id IN (1,3,35))


SELECT u.email,
       u.first_name
FROM   users u
       JOIN resources r
         ON u.id = r.user_id
WHERE  product_id IN ( 1, 3, 22, 35 )
GROUP  BY u.id,
          u.email,
          u.first_name
HAVING COUNT(DISTINCT product_id = 1)
       AND MAX(product_id) = 22  
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜