SQL for applying conditions to multiple rows in a join

前端 未结 11 2056
一个人的身影
一个人的身影 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:15

    I would do exactly what you are doing first, because that gets a list of all users with 'tag1' and a list of all users with 'tag2', but in the same response obviously. So, we have to add some more:

    Do a group by users (or users.id) and then having count(*) == 2. That will group duplicate users (which means those with both tag1 and tag2) and then the having-part will remove the ones with just one of the two tags.

    This solution avoids adding yet another join-statement, but honestly I'm not sure which is faster. People, feel free to comment on the performance-part :)

    EDIT: Just to make it easier to try out, here's the whole thing:

    SELECT * 
    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(*) = 2
    

提交回复
热议问题