0

我在努力解决高级查询时遇到了一些问题。

投票表中基本上有与给定配乐相对应的投票。我的查询需要根据获得的票数获得配乐的排名。

当表格中有投票时,我下面的方法工作得很好,但是当没有投票时,排名被赋予了一个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

4

3 回答 3

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;

见:http ://www.sqlfiddle.com/#!2/74698/2/0

于 2013-07-16T13:22:18.317 回答
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
于 2013-07-16T13:49:13.823 回答
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
于 2013-07-16T14:36:11.313 回答