1

所以,我有一个如下所示的 mysql 查询:

SELECT rewards.name, redemptions.points, redemptions.value
FROM rewards
INNER JOIN redemptions ON rewards.id = redemptions.reward_id;

问题是它会吐出这样的表格:

-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 2 |  100   |  10   |
-----------------------------
| Reward 2 |  100   |  10   |
-----------------------------
| Reward 3 |  250   |  20   |
-----------------------------

等等。理想情况下,我实际上希望它只列出一次,但对某些列求和。例如,它看起来像这样:

-----------------------------
| Reward 1 |  500   |  90   |
-----------------------------
| Reward 2 |  100   |  20   |
-----------------------------
| Reward 3 |  250   |  20   |
-----------------------------

它对第三列求和,但只列出前两列一次。我想也许工会会这样做,因为我知道它会忽略重复项,但我认为它在使用工会时也不起作用。

4

2 回答 2

2

使用SUM,并记得添加GROUP BY

SELECT rewards.name, redemptions.points, SUM(redemptions.value)
FROM rewards
INNER JOIN redemptions ON rewards.id = redemptions.reward_id
GROUP BY rewards.name;
于 2013-01-21T03:05:51.523 回答
1
SELECT  a.name, b.points, SUM(b.value)
FROM    rewards a
        INNER JOIN redemptions b
            ON a.id = b.reward_id
GROUP   BY a.name, b.points
于 2013-01-21T03:08:11.483 回答