使用 max 查找最常出现的 column_name

Find the most frequent seen column_name using max

我有一个 table 名为 food:

CREATE TABLE food
(
    name varchar(30) primary key,
    type varchar(30)
);

我想找到在这个table中出现次数最多的type

我可以使用

找到这个
SELECT type
FROM food
GROUP BY type
ORDER BY count(type) DESC
LIMIT 1

但是limit 1没有包含在标准中。如何使用 MAX 找到相同的结果?例如我想要像

这样的东西
SELECT type
FROM food
GROUP BY type
HAVING count(type) = MAX(count(type));
不允许

HAVING count(type) = MAX(count(type));

可能效率不高

SELECT type
FROM food
GROUP BY type
HAVING COUNT(type) =
(
    SELECT MAX(counting) FROM
    (
        SELECT COUNT(type) AS counting
        FROM food
        GROUP BY type
    ) t
)

使用 cte(常见的 table 表达式),其中 GROUP BYCOUNT:

with cte as
(
    SELECT type, count(*) as cnt
    FROM food
    GROUP BY type
)
select type from cte
where cnt = (select max(cnt) from cte)

如果出现平局,将 return 两行。

(我不知道与 Madhivanan 的回答相比,这是否具有相同或更好的性能。反正少打字。)