0

这是桌子

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_ids 的列表,其中name是 apple 并且 content_id 也有 ORANGE 与之相关联。

所以在这个例子中,如果我想知道哪个 content_ids 被标记为“apple”和“orange”,它会导致:

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

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

4

3 回答 3

1

你可以在它也有这样的名字的地方left join使用表格:content_id

select tbl.content_id
from tags tbl
left join tags tbl2 on tbl2.content_id = tbl.content_id and tbl2.name = 'orange'
where tbl.name = 'apple' and tbl2.name is not null
group by tbl.content_id

仅返回存在tbl2.name is not null子句指示的相应连接的行。

于 2012-08-15T09:02:00.990 回答
0
select content_id
from tags
where `name` in ('banana', 'orange')
group by content_id
having count(distinct `name`) >= 2 
于 2012-08-15T08:56:33.893 回答
0
select content_id from fruits 
where name in('apple','orange')
group by content_id
having COUNT(*)=2
于 2012-08-15T09:24:06.040 回答