我有一个高级查询的问题,我正在努力解决这个问题。
此时,投票表中的投票与给定的音轨相对应。我的查询需要根据已经获得的投票获得音轨的排名。
我的方法在表中有投票时效果很好,但当没有值时,等级被赋予NULL
值。
以下是查询:
SELECT soundtrack.*,
(SELECT WrappedQuery.rank
FROM (SELECT @rownum := @rownum + 1 AS rank,
prequery.soundtrack_id
FROM (SELECT @rownum := 0) sqlvars,
(SELECT Count(*),
soundtrack_id
FROM vote
GROUP BY vote.soundtrack_id
ORDER BY Count(*) DESC) prequery) WrappedQuery
WHERE WrappedQuery.soundtrack_id = soundtrack.id) AS rank
FROM soundtrack
WHERE soundtrack.id = 33
AND live = 1
ORDER BY rank ASC
我觉得问题与(SELECT COUNT(*))
部分有关,但到目前为止我所尝试的一切都没有用完。
希望有人可以解释我的问题。
修改 这是SQLFiddle http://www.sqlfiddle.com/#!2/c8db2/2/0
答案 0 :(得分:3)
这是一件好事:
SELECT soundtrack.*,
(SELECT WrappedQuery.rank
FROM (SELECT @rownum := @rownum + 1 AS rank,
prequery.soundtrack_id
FROM (SELECT @rownum := 0) sqlvars,
(
SELECT COALESCE(COUNT(vote.soundtrack_id),0) AS no_rows,
soundtrack.id AS soundtrack_id
FROM soundtrack
LEFT JOIN vote ON soundtrack.id=vote.soundtrack_id
GROUP BY soundtrack.id
ORDER BY 1 DESC
) prequery) WrappedQuery
WHERE WrappedQuery.soundtrack_id = soundtrack.id) AS rank
FROM soundtrack
ORDER BY rank ASC;
答案 1 :(得分:0)
我使用row_number函数在我自己的工作中有一些运气排名。但除此之外,合并功能可能会帮助你。
SELECT soundtrack.*, rankquery.rank
FROM (
SELECT row_number() over(partition by prequery.soundtrack_id order by prequery.num_votes) as rank,
prequery.soundtrack_id
FROM (
SELECT COALESCE(COUNT(*),0) as num_votes, soundtrack_id
FROM vote
GROUP BY soundtrack_id
ORDER BY num_votes DESC
) prequery
) rankquery
INNER JOIN soundtrack
rankquery.soundtrack_id = soundtrack.id
WHERE soundtrack.id = 33
AND live = 1
ORDER BY rank
答案 2 :(得分:0)
SELECT soundtrack.*, rankquery.rank
FROM(
SELECT prequery.*, @rownum := @rownum + 1 AS rank
(
SELECT COALESCE(Count(*),0) as num_votes,
soundtrack_id
FROM vote
GROUP BY soundtrack_id
ORDER BY num_votes DESC
) as prequery,
(SELECT @rownum := 0) as sqlvars
) rankquery
INNER JOIN soundtrack
rankquery.soundtrack_id = soundtrack.id
WHERE soundtrack.id = 33
AND soundtrack.live = 1
ORDER BY rankquery.rank ASC