我有一个历史记录表,我想用它来查找更新的特定项目的最新用户。这是我到目前为止的查询:
SELECT *
FROM `history`
WHERE `pKey`
IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 )
ORDER BY `history`.`time` DESC
LIMIT 0 , 30
这将返回每个pkey的多个历史记录结果。有没有办法将结果限制为仅从特定pkey的最新(基于时间)条目?
所以例如: 现在pkey 13309返回了多个结果。查询应该只返回它的最新结果。同样适用于13311 ......等。
答案 0 :(得分:3)
这应该做:
SELECT h.*
FROM `history` as h
INNER JOIN (SELECT `pkey`, MAX(`time`) as MaxTime
FROM `history`
WHERE `pkey` IN (13309, 13311, 13951, 14244, 1500,
15558, 15691, 15938, 9769)
GROUP BY `pkey`) as t
ON h.`pkey` = t.`pkey`
AND h.`time` = t.`MaxTime`
答案 1 :(得分:0)
这应该有效。只需对具有相同pkey的所有行进行分组。我认为这会奏效。评论反馈。
Select * from (
SELECT *
FROM `history`
WHERE `pKey`
IN ( 13309, 13311, 13951, 14244, 1500, 15558, 15691, 15938, 9769 )
ORDER BY `history`.`time` DESC) as t1 group by pKey