I'm having the following query, which supposedly will get the latest 3 comments for every update_id. It seemingly works until I discovered a logical issue where it gets the latest 3 comments regardless the update; it is supposed to get the latest 3 comments for every update_id. How can I achieve this? Obviously the limit(3) is wrong.

SELECT  `comms` . * ,  `usr`.`name` 
FROM (
`comms`
)
JOIN  `users` AS usr ON  `usr`.`id` =  `comms`.`user_id` 
WHERE  `update_id` 
IN (
'1451',  '1416',  '1186',  '1157',  '1150',  '1122',  '1057',  '914',  '850',  '816',  '794',  '790',  '749',  '746',  '745',  '744',  '740'
)
ORDER BY  `id` DESC 
LIMIT 3
有帮助吗?

解决方案

Try this:

SELECT A.*, u.name 
FROM (SELECT c.*, IF(@updateId = @updateId:=update_id, @idx:=@idx+1, @idx:=0) idx 
      FROM comms c, (SELECT @updateId:=0, @idx:=0) A
      WHERE update_id IN ('1451', '1416', '1186', '1157', '1150', '1122', '1057', '914', '850', '816', '794', '790', '749', '746', '745', '744', '740')
      ORDER BY update_id, id DESC   
    ) AS A 
INNER JOIN users AS u ON u.id = A.user_id
WHERE A.idx < 3
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top