用户提交了前5名并按人气排序

时间:2010-03-18 10:41:47

标签: php mysql sorting

数据库设置(MySQL)

表: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)是什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

下进行。

相关问题