0

How to select values in MySQL table by the count of a field in the same table ?

Example:

Table users has id, name, password, country 

I want to select all ids of only top 3 countries with highest users count to look like this:

country, id 

When I try this
WHERE country IN (SELECT country FROM USERS GROUP BY country ORDER BY COUNT(id) DESC LIMIT 3)

I get This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

Server version: 5.6.33-79.0 Percona Server

Nagy Wesley
  • 111
  • 2
  • 11

3 Answers3

0

How to select values in MySQL table by the count of a field in the same table?

Use the GROUP BY field HAVING COUNT(*)=123 aggregation expression after the WHERE clause if there is.

Rápli András
  • 3,869
  • 1
  • 35
  • 55
0

Try this:

SELECT country, id 
FROM
      (
         SELECT country,count(Id) as [NumberofUsers]
         FROM USERS 
         GROUP BY country 
                           ) X
INNER JOIN USERS U ON X.Country=U.Country
ORDER BY X.[NumberofUsers] DESC LIMIT 3
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38
0

Join with a subquery that gets the top 3 countries.

SELECT u.country, u.id
FROM users AS u
JOIN (SELECT country
      FROM users
      GROUP BY country
      ORDER BY COUNT(*) DESC
      LIMIT 3) AS u1
ON u.country = u1.country

Practically any use of WHERE column IN (SELECT ...) can be changed to a JOIN like this, and in many cases the performance is better.

Barmar
  • 741,623
  • 53
  • 500
  • 612