php - 用户提交前 5 名并按受欢迎程度排序

标签 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 分,“第二”栏奖励 4 分,“第三”栏奖励 3 分,依此类推...

所以,在我的示例中,它应该是这样的:

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

最佳答案

最好的解决方案是首先标准化您的数据。唯一实用的解决方案是模拟正确规范化数据库的行为。当然,该解决方案不应该涉及任何 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.

关于php - 用户提交前 5 名并按受欢迎程度排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2469097/

相关文章:

javascript - 附加到 div 标签 Jquery 中

php - 收到 POST 请求后更新网页

php - 基于字符串数组PHP和MySQL过滤记录

MySQL 数组字段上的内连接

python - mysqlfailover : No module named mysql. utilities.common.tools

java - 按值对 Map<Key, Value> 进行排序

php-webdriver : wait for browser response after submitting form using click()

php - 使用 php 检测页面文件名?

javascript - 在 Immutable.js 中按特定键对orderedMap 进行排序

javascript - 在 Mongoose 中对子文档进行排序