我需要执行查询才能获得孩子们最喜欢的糖果,这就是我所拥有的:
SELECT COUNT(*) as counts,candies.name
FROM candies
INNER JOIN kid_candy ON kid_candy.candy_id = candies.id
INNER JOIN kids ON kids.id = kid_candy.kid_id
GROUP BY candies.name
会返回:
counts | name
--------+---------
3 | snowbear
3 | whiterabbit
2 | lollipop
我想看到的只是
counts | name
--------+---------
3 | snowbear
3 | whiterabbit
那我的查询应该是什么?
答案 0 :(得分:3)
所以,首先让我们得到每个糖果名称的计数(tmp_table
),然后得到所有糖果的最大数量(max_cnt
),最后把它们放在一起,从{{1获得糖果来自tmp_table
表...
max(counts)
max_cnt
答案 1 :(得分:1)
假设孩子和糖果之间的经典的n:m关系,如下所示:
您应该在问题中提供此类详细信息。
SELECT c.id, kc.counts, c.name
FROM (
SELECT candy_id AS id, count(*) AS counts
, rank() OVER (ORDER BY count(*) DESC) AS rnk
FROM kid_candy
GROUP BY 1
) kc
JOIN candies c USING (id)
WHERE kc.rnk = 1;
这应该比具有两个CTE和不必要的连接的查询快得多。
按candies.name
分组可能是错误的(而且更贵)。该名称可能不是唯一的。使用主键列,可能是candies.id
假设参照完整性,我们根本不需要加入表kids
。
由于我们需要检查整个表格,因此首先聚合和加入到糖果以获取name
更快后
您可以在聚合函数上运行窗口函数:
答案 2 :(得分:0)
试试这个
SELECT * FROM
(
SELECT COUNT(*) AS Counts,candies.name FROM candies
INNER JOIN kid_candy ON kid_candy.candy_id = candies.id
INNER JOIN kids ON kids.id = kid_candy.kid_id
GROUP BY candies.name
) T1 JOIN
SELECT MAX(counts) MaxCount FROM
(
SELECT COUNT(*) AS Counts,candies.name FROM candies
INNER JOIN kid_candy ON kid_candy.candy_id = candies.id
INNER JOIN kids ON kids.id = kid_candy.kid_id
GROUP BY candies.name
) T1 ON T1.counts =T2.MaxCount
答案 3 :(得分:0)
进行子选择
Select max(counts)
(select COUNT(*) as counts,candies.name from candies
INNER JOIN kid_candy ON kid_candy.candy_id = candies.id
INNER JOIN kids ON kids.id = kid_candy.kid_id
GROUP BY candies.name)