我到处都是。除了两个问题之外,下面的MySql查询适用于我。
1)我想确保每个类别只显示一个结果(我有5个类别),我尝试使用DISTINCT但明显误解了那个。
2)我希望能够在sql查询之外返回howmany值:
"SELECT DISTINCT category_id, video_id, date_added, COUNT(video_id) AS howmany
FROM votes
WHERE date_added BETWEEN SYSDATE() - INTERVAL 7 DAY AND SYSDATE()
GROUP BY video_id
ORDER BY howmany DESC, video_id
LIMIT 5";
我的投票表看起来像这样:
id | video_id | category_id | date_added
编辑: 预期产出 -
video_id 2 category_id 4投票数500
video_id 5 category_id 1投票数377
video_id 88 category_id 3投票数25
video_id 45 category_id 5投票数23
video_id 9 category_id 2投票数2
显示过去7天内每个类别中投票最多的视频。
答案 0 :(得分:2)
如果你想进一步打破结果,很可能你会想GROUP BY category_id
,甚至GROUP BY category_id, video_id
。
答案 1 :(得分:2)
如果每个类别只需要1个结果,则必须按类别分组。但由于每个类别可能有多个video_id,因此除非使用GROUP_CONCAT,否则最终会从类别中获取一个随机视频。
如果您只想获得列值的明确计数,请将DISTINCT关键字放在count函数中:
COUNT( DISTINCT video_id )
答案 2 :(得分:1)
SELECT DISTINCT category_id, video_id, date_added, COUNT(video_id) AS howmany
在功能上等同于
GROUP BY category_id, video_id, date_added, COUNT(video_id)
你说“我想确保每个类别只显示一个结果”,所以你可能想要这样的东西:
SELECT category_id, video_id, date_added, COUNT(video_id) AS howmany
FROM votes
WHERE date_added BETWEEN SYSDATE() - INTERVAL 7 DAY AND SYSDATE()
GROUP BY category_id
ORDER BY howmany DESC, video_id
LIMIT 5;
答案 3 :(得分:1)
MySQL没有您用于这类情况的分析功能 - 使用:
SELECT x.video_id,
x.category_id,
x.howmany
FROM (SELECT t.video_id,
t.category_id,
COUNT(*) AS howmany,
CASE
WHEN @category = t.category_id THEN @rownum
ELSE @rownum := @rownum + 1
END AS rank,
@category := t.category_id
FROM VOTES t
JOIN (SELECT @rownum := 0, @category := -1) r
WHERE t.date_added BETWEEN SYSDATE() - INTERVAL 7 DAY AND SYSDATE()
GROUP BY t.video_id, t.category_id
ORDER BY t.category_id, howmany DESC) x
WHERE x.rank = 1
ORDER BY x.howmany DESC
LIMIT 5