用于匹配多个列值的SQL查询

时间:2012-11-14 08:08:23

标签: mysql sql

我无法理解以下问题。

鉴于以下表结构和数据,我如何选择与两个标记匹配的记录。例如:

+-----------------+------------------+
|  collection_id  |         tag      |
+-----------------+------------------+
|        1        |    advertising   |
|        1        |     tutorials    |
|        2        |    advertising   |
|        2        |       coding     |
+-----------------+------------------+

如果我搜索广告&&教程,它应该返回collection_id = 1,而不是collection_id = 2。

欢迎提出任何指示。

1 个答案:

答案 0 :(得分:6)

SELECT collection_ID
FROM tableName
WHERE tag IN ('advertising','tutorials')
GROUP BY collection_ID
HAVING COUNT(*) = 2

如果未在每个unique

的代码上指定collection_ID约束
SELECT collection_ID
FROM tableName
WHERE tag IN ('advertising','tutorials')
GROUP BY collection_ID
HAVING COUNT(DISTINCT tag) = 2