0

我想返回投票最多的前 5 个项目,按投票数排序。我想最好的方法是将每一行的votes_upand相加votes_down,然后取其中的前 5 个并将其与另一个表连接起来。

这是我现有的表,Items.ID 映射到 Votes.item_ID:

Items
+----+--------+---------+
| ID |  name  | site_ID |
+----+--------+---------+
| 10 | box    |     111 |
| 11 | hammer |     222 |
| 12 | drill  |     333 |
| 13 | nail   |     444 |
+----+--------+---------+

Votes
+----+---------+----------+------------+
| ID | item_ID | votes_up | votes_down |
+----+---------+----------+------------+
|  1 |      10 |       25 |         20 |
|  2 |      11 |      200 |        100 |
|  3 |      12 |      100 |         50 |
|  4 |      13 |       50 |         20 |
+----+---------+----------+------------+

这些是我想要返回的结果:

+--------+-------+
|  name  | votes |
+--------+-------+
| hammer |   100 |
| drill  |    50 |
| nail   |    30 |
| box    |     5 |
+--------+-------+
4

2 回答 2

1
SELECT   Items.name, votes_up-votes_down AS votes_num
FROM     Items, Votes
WHERE    Items.id = Votes.item_id
ORDER BY votes_num DESC
LIMIT    5;

数据库先做JOINthen LIMIT,否则很可能会丢失元组。EXPLAIN SELECT ...如果您使用的是 MySQL 或 PostgreSQL,则可以使用语句验证这一点。如果你想先做top 5,你必须手动做:

SELECT I.name, V.votes_num AS votes_num
FROM   Items I, 
  (SELECT item_ID, votes_up-votes_down AS votes_num
   FROM   Votes ORDER BY votes_num DESC LIMIT 5) V
WHERE  I.ID = V.item_ID
ORDER BY votes_num DESC;

查看此演示;它返回你想要的结果。

NAME    VOTES_NUM
hammer  100
drill   50
nail    30
box     5
于 2013-05-12T22:04:09.430 回答
1
SELECT i.name AS name, v.votes_up-v.votes_down AS votes
FROM items AS i
JOIN votes AS v ON v.item_id=i.id
ORDER BY votes DESC
LIMIT 5 ;

我认为SELECT TOP 5是 MS SQL 语法。

于 2013-05-12T22:09:02.653 回答