簡體   English   中英

選擇不同的值ColumnA,而ColumnB = Value1和ColumnB = Value2

[英]Select Distinct values ColumnA while ColumnB = Value1 and ColumnB = Value2

這是桌子

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 s的列表,其中name是apple並且content_id還與ORANGE綁定。

因此,在此示例中,如果我想知道哪些content_id已被“ apple”和“ orange”標記,則會導致:

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

由於這些是被相應標記的僅有的兩個content_id。 最好的方法是什么?

您可以在content_idleft 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指示有相應tbl2.name is not null子句。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM