Select only those entries that have the same foreign_id twice

I have a mysql InnoDB table with the following structure:

id artist_id 

There are many entries, most artist_ids are there 15 times. But some of them are there only twice. I need to get them.

I came up with the following, to no avail:

 SELECT artist_id FROM matches HAVING COUNT(artist_id)=2 

It returns 0 rows, although there are artist_ids that only appear in the table twice. How can I get them?

+4
source share
2 answers


Hello,
I would use this:
SELECT artist_id,count(*) FROM matches GROUP BY artist_id HAVING COUNT(*)=2
because HAVING is a filter of results.

C =2 you will find those that exist exactly twice.

+5
source
 select artist_id, count(id) as num from matches group by artist_id having num = 2; 
+1
source

Source: https://habr.com/ru/post/1433669/


All Articles