Mysql - select ids that match all tags

后端 未结 1 753
青春惊慌失措
青春惊慌失措 2021-02-14 03:46

I have a cross-reference table:

ID | tag
1  | 4
1  | 5
1  | 6
2  | 4
2  | 5
2  | 8
3  | 2

I need to select the IDs that match all of a

相关标签:
1条回答
  • 2021-02-14 04:09

    The idea of the query is that you need to match the number of records to the number of values you have provided in the WHERE clause.

    SELECT ID
    FROM tableName
    WHERE tag IN (4, 8)
    GROUP BY ID
    HAVING COUNT(*) = 2
    
    • SQLFiddle Demo

    if unique constraint was not specified on tag for every ID, then DISTINCT is needed

    SELECT ID
    FROM tableName
    WHERE tag IN (4, 8)
    GROUP BY ID
    HAVING COUNT(DISTINCT tag) = 2
    
    0 讨论(0)
提交回复
热议问题