获取价值,在列中重复更多次

时间:2012-11-03 18:44:09

标签: mysql

给定表menu,在他的列continent中,例如在他身上是这个数据

continent
----------
africa
africa
europe
europe
europe

我想要获取大陆名称,这在列中的次数更多,结果必须是europe

我写了查询,但我认为我的查询很难,并且必须存在这样的情况下更容易解决的问题。是一些想法?

这是我的查询

    SELECT continent FROM (
        SELECT continent, COUNT(continent) AS cnt FROM menu GROUP BY continent
    ) AS t
    WHERE cnt = (
        SELECT MAX(cnt) FROM ( 
            SELECT  COUNT(continent) AS cnt FROM menu GROUP BY continent
        ) AS t2
    )

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT continent FROM (
    SELECT continent, COUNT(continent) AS cnt
    FROM menu
    GROUP BY continent
) AS t
ORDER BY cnt DESC
LIMIT 0, 1

我认为您也可以在一个查询中执行此操作:

SELECT continent, COUNT(continent) AS cnt
FROM menu
GROUP BY continent
ORDER BY cnt DESC
LIMIT 0, 1

此致


更新:

SELECT continent
FROM menu
GROUP BY continent
HAVING count(continent) = 
(
    SELECT COUNT(continent) AS cnt
    FROM menu
    GROUP BY continent
    ORDER BY cnt DESC
    LIMIT 0, 1
)

内部查询返回最多重复项目;然后,该值将应用于应用于HAVING运算符的外部查询,以仅返回完全重复该时间的项目。这适用于mysql,我不确定其他SQL方言。