SQL for applying conditions to multiple rows in a join

前端 未结 11 1898
一个人的身影
一个人的身影 2020-11-29 22:55

I think I found the answer to my question, I\'m just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:<

相关标签:
11条回答
  • 2020-11-29 23:16
    SELECT Users.id, count(tags.*) as tagCount
    FROM Users Inner join tags
    ON tags.user_id = users.id
    WHERE tags.name='tag1' OR tags.name='tag2'
    GROUP BY Users.id
    HAVING count(tags.*) = 2
    
    0 讨论(0)
  • 2020-11-29 23:16

    Give this a try

    SELECT *
    FROM users
    INNER JOIN tags ON tags.user_id = users.id
    WHERE users.id in
        (
        SELECT user_id
        FROM tags
        WHERE name IN ('tag1', 'tag2')
        GROUP BY user_id
        HAVING COUNT(*) = 2
        )
    
    0 讨论(0)
  • 2020-11-29 23:17
    select * from users u
    where 2 = (select count(*) from tags t where t.user_id = u.id and name in ('tag1','tag2'))
    

    Assuming that any given tag can only be present once per user.

    0 讨论(0)
  • 2020-11-29 23:20

    You'll want to join the tags table again.

    SELECT * FROM users
    INNER JOIN tags as t1 on t1.user_id = users.id and t1.name='tag1'
    INNER JOIN tags as t2 on t2.user_id = users.id and t2.name='tag2'
    
    0 讨论(0)
  • 2020-11-29 23:20

    You'll need to check for the existence of two rows, rather than being able to do a simple IN (which will only check the values within each joined record). Maybe something like:

    SELECT * 
    from users
    WHERE EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag1')
      AND EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag2');
    
    0 讨论(0)
提交回复
热议问题