开发者

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

开发者 https://www.devze.com 2023-03-02 17:52 出处:网络
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 BU

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

精彩评论

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