2012-09-26 196 views
0

這是我mat_likes表:MySQL的:選擇查詢

mat_id| yes| no 
    1 | 1 | 0 
    1 | 1 | 0 
    1 | 1 | 0 
    2 | 1 | 0 
    3 | 1 | 0 
    4 | 1 | 0 
    4 | 1 | 0 

如何選擇這些材料,它們具有最yes = 1mat_id。減去結果Еxample:

  1. mat_id = 1,因爲有總yes = 3
  2. mat_id = 4,因爲有總yes = 2
  3. mat_id = 3,因爲有總yes = 1
  4. mat_id = 2,因爲有總yes = 1

回答

3
SELECT mat_id,SUM(yes) yes_sum 
FROM mat_likes 
GROUP BY mat_id 
ORDER BY yes_sum DESC 

將返回一個結果集,其中每個mat_id的總和爲yes,最高的總和在上面!

編輯:添加mat_id字段列表

0
SELECT mat_id, SUM(yes) yes_sum 
FROM mat_likes 
GROUP BY mat_id 
ORDER BY yes_sum DESC, mat_id DESC