2016-08-24 98 views
0

我如何寫這樣的查詢:MySQL:如果IN()語句在Select中?我如何查詢?

SELECT userid, 
(IF field IN(1,2,3,900,658,4,5,6,9,10,11,12,13,10025,14,15,16,17,18,19) score = score +20, ELSE IF field IN(23,45,67,777,53,54) score = score + 40, 
    ELSE IF field IN(120,332,563,334,634,423,333) score = score + 60) AS score 
WHERE field IN(1,2,3,900,658,4,5,6,9,10,11,12,13,10025,14,15,16,17,18,19,23,45,67,777,53,54,120,332,563,334,634,423,333) 
GROUP BY userid ORDER BY score DESC 

我試圖找出誰擁有字段設置爲給定的數字之一的所有用戶。某些數字有不同的分數(20分,40分和60分),所以我需要合計分數以獲得每個用戶標識的總分,然後按總分對用戶進行排名。

+0

'如果()'在'使用select'查詢是不是一個編程流程控制語句。這是一個功能。 'if(something_that_returns_a_boolean,truevalue,falsevalue)'。 –

回答

1

你可能會尋找這樣的:

SELECT userid, 
     sum(
      CASE 
       WHEN field IN (1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19) THEN 20 
       WHEN field IN (23,45,67,53,54) THEN 40 
       ELSE 60 
      END) AS score 
FROM  mytable 
WHERE field IN (1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19,23,45,67,53,54,120, 
        332,563,334,634,423,333) 
GROUP BY userid 
ORDER BY score DESC 
+0

非常好,我認爲Case/When語句正是我所期待的!謝謝,親切的問候 – peppy

0

您從表遺漏日,你可以做的情況下

select UserId, 
    case 
     when field < 20 then Score + 20 
     when field IN(23,45,67,53,54) then Score + 40 
     else score + 60 
     end as Score 
FROM mytable 
where field IN(1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19,23,45,67,53,54,120,332,563,334,634,423,333) 
group by UserId 
order by Score desc