MySQL子查询Sum&限制

时间:2012-10-16 21:14:29

标签: mysql sum limit

我想要做的是抓住最后4个人_id并将它们相加。这是我当前的MySQL查询。我最终得到的是person_id 23 = 4.当我将LIMIT更改为7时,我最终得到person_id 23 = 6,而person_id 24 = 2.我需要的是

person_id 23 = 4
person_id 24 = 8
person_id 25 = 12

我做错了什么?

SELECT SUM(ms.value) AS value, ms.person_id
FROM
    (SELECT mst.value, mst.id, mst.person_id
    FROM match_statistic AS mst
    WHERE mst.person_id IN (23,24,25)
    ORDER BY mst.id ASC
    LIMIT 4) AS sub
INNER JOIN match_statistic AS ms ON sub.id = ms.id
GROUP BY ms.person_id


  match_statistic table
| id | person_id | value |
| 10 |    23     |   1   |
| 11 |    23     |   1   |
| 12 |    23     |   1   |
| 13 |    23     |   1   |
| 14 |    23     |   1   |
| 15 |    23     |   1   |
| 16 |    24     |   2   |
| 17 |    24     |   2   |
| 18 |    24     |   2   |
| 19 |    24     |   2   |
| 20 |    24     |   2   |
| 21 |    24     |   2   |
| 22 |    25     |   3   |
| 23 |    25     |   3   |
| 24 |    25     |   3   |
| 25 |    25     |   3   |
| 26 |    25     |   3   |
| 27 |    25     |   3   |

2 个答案:

答案 0 :(得分:2)

您也可以执行此操作检查SQL FIDDLE

SELECT SUM(ms.value) AS value, ms.person_id FROM (
SELECT a.id, a.person_id, a.value, count(*) as row_number 
FROM MATCH_STATS a
JOIN MATCH_STATS b ON a.person_id = b.person_id AND a.id <= b.id
GROUP BY a.id, a.person_id, a.value
) ms  WHERE ms.person_id IN (23,24,25) and row_number < 5
GROUP BY ms.person_id

OR

对于您当前的查询将内部查询更改为

SELECT mst.value, mst.id, mst.person_id
    FROM match_statistic AS mst
    WHERE mst.person_id IN (23)
    ORDER BY mst.id ASC
    LIMIT 4

UNION ALL
SELECT mst.value, mst.id, mst.person_id
    FROM match_statistic AS mst
    WHERE mst.person_id IN (24)
    ORDER BY mst.id ASC
    LIMIT 4

UNION ALL
SELECT mst.value, mst.id, mst.person_id
    FROM match_statistic AS mst
    WHERE mst.person_id IN (25)
    ORDER BY mst.id ASC
    LIMIT 4

答案 1 :(得分:0)

尝试这样的事情。在不必知道列表中的组数量的情况下,它会更加通用。答案就是结果。我刚给你留了一些额外的行来看看行为。这并不意味着是最终的解决方案。只是朝着正确的方向大力推进。

请注意,如果数据库具有该支持,则可以使用窗口函数。

SELECT t1.id
     , SUM(t2.value)
     , t1.person_id
     , COUNT(t2.id) AS cnt
  FROM theTable AS t1
  LEFT JOIN theTable AS t2
    ON (t1.id) <= (t2.id)
   AND t1.person_id = t2.person_id
 GROUP BY t1.id
        , t1.person_id
HAVING cnt <= 4 AND t1.person_id IN (23, 24, 25)
 ORDER BY t1.person_id, cnt
 ;