2010-03-18 50 views
0

數據庫設置(MySQL的)用戶提交的前5名和排序按熱門程度

表:top_fives

id, uid, first,  second, third, fourth, fifth, creation_date 
1, 1, cheese, eggs, ham,  bacon, ketchup, 2010-03-17 
2, 2, mayonaise, cheese, ketchup, eggs, bacon, 2010-03-17 

用戶可以提交他們的前5某一主題的。現在我想根據受歡迎程度排序的前五名的總結。

每列都有自己的點值。列「第一」是獎勵5分,「第二」四點,「第三」三個點,等等...

所以,在我的例子應該是這樣的:

1 Cheese  (9 points = 5 + 4 -> 1 time in 'first' column and 1 time in 'second' column) 
2 Eggs  (6 points) 
3 Mayonaise (5 points) 
4 Ketchup (4 points) 
5 Bacon  (3 points) 
6 Ham  (3 points) 

什麼是這種情況下最簡單的解決方案(PHP)?

+0

@Bundy:出於好奇,你試試我的查詢嗎? – 2010-03-18 11:25:14

回答

1

最好的解決辦法是擺在首位,以已恢復正常數據。唯一可行的解​​決方案是模擬正常規範化數據庫的行爲。當然,解決方案不應涉及任何PHP代碼,並應在數據庫上進行:

SELECT type, SUM(score) 
FROM 
(
(SELECT first as type, COUNT(*)*5 as score 
FROM top_fives 
GROUP BY first 
) UNION 
(SELECT second AS type, COUNT(*)*4 as score 
FROM top_fives 
GROUP BY second 
) UNION 
(SELECT third AS type, COUNT(*)*3 as score 
FROM top_fives 
GROUP BY third 
) UNION 
(SELECT fourth AS type, COUNT(*)*2 as score 
FROM top_fives 
GROUP BY fourth 
) UNION 
(SELECT fifith AS type, COUNT(*) as score 
FROM top_fives 
GROUP BY fifth 
) 
) 
GROUP By type 
ORDER BY SUM(score) DESC; 

C.

+0

謝謝,這個伎倆!該表需要一個別名,雖然:) – Bundy 2010-03-18 11:23:38

1

解決方案將正常化你的表(見下文)。

如果你沒有,你應該能夠做到可以:

Select name, Sum(points) total_points 
From (
    Select first name, 5 points 
    From top_fives 
    Union 
    Select second name, 4 points 
    From top_fives 
    Union 
    ... 
) 
Group By name 
Order By total_points Desc 

標準化的解決方案

food 

food_id, food_name 
1  cheese 
2  eggs 
3  ham 
... 

food_rating 
------ 
uid, food_id, points 
1 1  5 
1 2  4 
1 3  3 
2 1  4 

Select f.food_name, Sum(r.points) total_points 
From food_rating r 
Join food f On (f.food_id = r.food_id) 
Group By food_name 
Order By total_points Desc