[英]Find duplicates of one column but only return results if another column has same value
我想找到重復(重復)的給定列的值,但只有在行中的另一列相同時才返回重復。
也許一個例子會更清楚。 給定一個名為filters的表,我有3列(id,name,filter_type):
DESCRIBE filters;
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| filter_type | varchar(255) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
現在我想選擇所有重復的filter_types。 很容易:
SELECT COUNT(*) as count, filter_type
FROM filters
GROUP BY filter_type_type HAVING count > 1;
+-------+-----------------+
| count | filter_type |
+-------+-----------------+
| 5 | Contact |
+-------+-----------------+
但是我想只返回重復,如果名稱列值是所有組的SAME。 因此,在上面的結果中,我們重復“聯系”。 它重復5次。 但是,如果所有5條記錄都具有相同的列值,我只想返回此結果。
SELECT name FROM filters WHERE filter_type = 'Contact';
+---------------------------+
| name |
+---------------------------+
| All |
| All |
| New |
| All |
| New |
+---------------------------+
由於5條記錄的名稱值不相同,我不想返回“聯系人”filter_type。 但如果他們都一樣,那么我想要歸還它。
我在考慮使用子查詢,但不知道如何連接它們。 我怎么能這樣做?
您可以使用聚合以及having
子句:
select filter_type
from filters
group by filter_type
having count(*) > 1 and
min(name) = max(name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.