简体   繁体   中英

Return all records in a table with count > 1 for specific field in mysql

I know how to count records in a table based on a distinct value in a field but I am trying now to return all the records in the table that have duplicate values in a given field (without seeing the records that do not) so I can do some analysis of those records. Can I use count this way? I tried

where count (distinct FIELD_A)>1

but it said I was using group incorrectly.

To restrict / filter the query output after aggregation has been performed, use a HAVING clause.

The WHERE clause is used to restrict / filter the query output BEFORE aggregation is performed (so if you had some rows you did not want to include in the COUNT, you can use the WHERE clause to filter them out).

Also you should not be using DISTINCT here, it will REMOVE all the duplicates before calculating the COUNT.

Try this:

SELECT
    FIELD_A, count(*) no_of_records
FROM table
GROUP BY FIELD_A
HAVING count(*) > 1;

Use having statement

Select Field_Blah, Count(Distinct Field_A)
From table_a
group by Field_Blah
having Count(Distinct Field_A) > 1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM