SQL SUM前5个值然后JOIN结果

时间:2013-05-12 22:02:00

标签: mysql sql join sum

我想返回投票最多的5个投票项目,按投票数排序。 我想最好的方法是将每一行的votes_upvotes_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 |
+--------+-------+

2 个答案:

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

数据库首先JOIN然后LIMIT,否则可能会丢失元组。如果您使用的是MySQL或PostgreSQL,则可以使用EXPLAIN SELECT ...语句对此进行验证。如果你想先做前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;

结帐demo;它返回你想要的结果。

NAME    VOTES_NUM
hammer  100
drill   50
nail    30
box     5

答案 1 :(得分: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语法。