I want to find the values of a given column that repeat (duplicate), but only return the repeats if another column in the row is the same.
Perhaps an example would be clearer. Given a table called filters, I have 3 columns (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 | |
+-------------------+--------------+------+-----+---------+----------------+
Now I want to select all filter_types that repeat. Easy enough:
SELECT COUNT(*) as count, filter_type
FROM filters
GROUP BY filter_type_type HAVING count > 1;
+-------+-----------------+
| count | filter_type |
+-------+-----------------+
| 5 | Contact |
+-------+-----------------+
But I want to only return the repeat if the name column values are the SAME for all of the group. So in the result above, we have repeat 'Contact'. It repeats 5 times. But I only want to return this result if all 5 records have the same name column value.
SELECT name FROM filters WHERE filter_type = 'Contact';
+---------------------------+
| name |
+---------------------------+
| All |
| All |
| New |
| All |
| New |
+---------------------------+
Since the name values are not the same for the 5 records, I do not want to return the 'Contact' filter_type. But if they were all the same, then I would want to return it.
I was thinking to use subqueries, but not sure how to connect them. How could I do this?
You can use aggregation for this, along with a having
clause:
select filter_type
from filters
group by filter_type
having count(*) > 1 and
min(name) = max(name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.