2013-07-16 55 views
0

我有一個高級查詢的問題,我正在努力讓我的腦袋周圍。COUNT()與空值,在子查詢中

本質上,票數表中有與選定電影配樂相對應的票數。我的查詢需要根據已獲得的投票來獲得配樂的排名。

下面我的方法工作得很好,當表中有投票時,但是當沒有內容時排名被賦予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

回答

3

,一個是GOOD:

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; 

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

+0

我還沒有嘗試,但我有這樣的想法,而不架構.... – jaczes

+0

與小改工作。看到我的問題。謝謝。 – freshnode

+0

我害怕我錯了,別人正在處理數據並投票,使查詢工作。還有誰? – freshnode

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 
+0

嗨,從那得到一個語法錯誤,任何想法? – freshnode

+0

具體來說:'#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第4行使用'(由prequery.soundtrack_id order by prequery.num_votes劃分的分區)'作爲等級, p'在第4行' – freshnode

+0

My fault,MySQL does not recognized the row_number函數。你在使用變量時是正確的。請參閱其他文章。 – tkendrick20

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 
+0

這裏有一個語法錯誤,我真的不知道問題在哪裏? – freshnode

+0

我剛剛重新編寫了一段代碼,試圖解決語法錯誤 – tkendrick20

+0

仍然是語法錯誤,下面是sqlfiddle:http://www.sqlfiddle.com/#!2/c8db2/2/0 – freshnode