2

我想要做的是获取最后 4 个 person_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   |
4

2 回答 2

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

或者

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

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
于 2012-10-16T21:48:38.330 回答
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
 ;
于 2012-10-16T22:25:39.573 回答