这是桌子

mysql> desc tags;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| content_id | int(11)      | NO   |     | NULL    |                |
| name       | varchar(100) | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)


一些数据

mysql> select * from tags;
+----+------------+---------------+
| id | content_id | name          |
+----+------------+---------------+
|  1 |         36 | banana        |
|  2 |         36 | strawberry    |
|  3 |         36 | orange        |
|  4 |         36 | apple         |
|  5 |         36 | watermelon    |
|  6 |         37 | qiwi          |
|  7 |         37 | apple         |
|  8 |         37 | orange        |
|  9 |         37 | bed           |
| 10 |         38 | grape         |
| 11 |         38 | apple         |
+----+------------+---------------+
11 rows in set (0.00 sec)


我想要的是获取唯一的content_id列表,其中的name是苹果,而content_id还具有与之关联的ORANGE。

因此,在此示例中,如果我想知道同时用“ apple”和“ orange”标记了哪些content_id,则会导致:

+------------+
| content_id |
+------------+
|         36 |
|         37 |
+------------+


因为只有这两个content_id被相应地标记了。最好的方法是什么?

最佳答案

select content_id
from tags
where `name` in ('banana', 'orange')
group by content_id
having count(distinct `name`) >= 2

08-08 08:03