选择Distinct values ColumnA,ColumnB = Value1,ColumnB = Value2

时间:2012-08-15 08:52:38

标签: mysql

这是表格

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绑在一起。

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

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

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

3 个答案:

答案 0 :(得分: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子句指示的对应连接的行。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

select content_id from fruits 
where name in('apple','orange')
group by content_id
having COUNT(*)=2