我想找出给定列中重复(复制)的值,但仅当该行中的另一列相同时才返回重复。
也许举个例子会更清楚。给定一个名为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 |
+-------+-----------------+但我只想在所有组的name列值都相同的情况下才返回repeat。因此,在上面的结果中,我们有重复的'Contact‘。它会重复5次。但是我只想在所有5条记录都有相同的名称列值的情况下返回这个结果。
SELECT name FROM filters WHERE filter_type = 'Contact';
+---------------------------+
| name |
+---------------------------+
| All |
| All |
| New |
| All |
| New |
+---------------------------+由于5条记录的name值不同,因此我不想返回'Contact‘filter_type。但如果它们都是一样的,那么我会想要返回它。
我在考虑使用子查询,但不确定如何连接它们。我怎么能这样做呢?
发布于 2019-04-23 10:35:57
为此,您可以使用aggregation,以及一个having子句:
select filter_type
from filters
group by filter_type
having count(*) > 1 and
min(name) = max(name)https://stackoverflow.com/questions/55803488
复制相似问题