1

我在 php 和 mysql 中创建了一个投票系统。当用户对 id 进行投票时,会在引用 FK media_id 的“votes”中插入一条记录。然后,当我显示条目时,我使用此查询来获取每个条目的票数:

$sql = "SELECT COUNT(*) FROM insta_votes WHERE media_id ='".$mediaid."'";
if ($res = $db->query($sql)) {
    return $res->fetchColumn();
}
return 0;

这很好用,但我希望能够按他们拥有的票数对结果进行排序。最好只使用一个查询。我怎样才能做到这一点?

这些表的结构如下:

votes table
+-----------+--------------+------+-----+-------------------+----------------+
| Field     | Type         | Null | Key | Default           | Extra          |
+-----------+--------------+------+-----+-------------------+----------------+
| id        | int(11)      | NO   | PRI | NULL              | auto_increment |
| media_id  | varchar(255) | NO   |     | NULL              |                |
| ip        | varchar(20)  | NO   |     | NULL              |                |
| c_time    | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
| sessionid | varchar(30)  | NO   |     | NULL              |                |
+-----------+--------------+------+-----+-------------------+----------------+

entries table
+---------------+--------------+------+-----+-------------------+-------+
| Field         | Type         | Null | Key | Default           | Extra |
+---------------+--------------+------+-----+-------------------+-------+
| page_id       | int(11)      | NO   | MUL | NULL              |       |
| media_id      | varchar(255) | NO   | PRI | NULL              |       |
| url           | varchar(255) | NO   |     | NULL              |       |
| c_time        | datetime     | NO   |     | NULL              |       |
| likes         | int(11)      | YES  |     | NULL              |       |
| deleted       | tinyint(1)   | NO   |     | 0                 |       |
| inserted_time | timestamp    | YES  |     | CURRENT_TIMESTAMP |       |
| numReports    | int(11)      | NO   |     | 0                 |       |
+---------------+--------------+------+-----+-------------------+-------+

谢谢!

4

3 回答 3

4

如果我正确理解表格(我可能不会),每entries行可能引用多votes行。在这种情况下,您需要的查询将如下所示:

SELECT
  entries.page_id,
  COUNT(*) AS VoteCount
FROM entries
INNER JOIN votes ON entries.media_id = votes.media_id
GROUP BY entries.page_id
ORDER BY VoteCount

如果您将其他entries列添加到SELECT列表中,请务必将它们也添加到GROUP BY列表中。


附录:@JuanPabloCalifano 正确地指出,这个查询不包括零票的条目。以下是包含它们的方法:

SELECT
  entries.page_id,
  COALESCE(COUNT(votes.id), 0) AS VoteCount
FROM entries
LEFT JOIN votes ON entries.media_id = votes.media_id
GROUP BY entries.page_id
ORDER BY VoteCount
于 2013-08-06T12:18:45.860 回答
0
SELECT COUNT(*) as CNT, `media_id` FROM `insta_votes` GROUP BY `media_id` order by 1;
于 2013-08-06T12:16:59.217 回答
0
SELECT COUNT(*), media_id FROM insta_votes 
GROUP BY media_id 
ORDER BY COUNT(*);"
于 2013-08-06T12:17:36.317 回答