如何通过提交的计数选择值?

时间:2016-12-14 22:48:12

标签: mysql sql

如何通过同一个表中的字段计数在MySQL表中选择值?

示例:

Table users has id, name, password, country 

我想选择只有最高用户数的前3个国家/地区的所有ID,如下所示:

country, id 

当我试试这个时 WHERE country IN (SELECT country FROM USERS GROUP BY country ORDER BY COUNT(id) DESC LIMIT 3)

我得到This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

服务器版本:5.6.33-79.0 Percona Server

3 个答案:

答案 0 :(得分:0)

  

如何通过中的字段计数在MySQL表中选择值   同桌?

如果有GROUP BY field HAVING COUNT(*)=123子句,请使用WHERE聚合表达式。

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

加入获得前三个国家的子查询。

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

实际上WHERE column IN (SELECT ...)的任何使用都可以更改为JOIN,在许多情况下效果会更好。