如何删除SQL结果中最旧的条目?

时间:2017-06-14 11:40:22

标签: php mysql pdo

我想仅针对所有项目获取最新报告,但仅针对每个item_id最新报告。 这是我目前的解决方案:

SELECT distinct * FROM t.reports ORDER BY created DESC LIMIT 100

我的表格包含以下列:

id | user | item_id |  created
'2', '1',   '2643',  '2017-06-13 16:28:34'
'3', '1',   '19333', '2017-06-13 19:26:56'
'4', '1',   '19333', '2017-06-13 19:29:24'
'5', '1',   '1319',  '2017-06-13 19:29:56'
'6', '1',   '1319',  '2017-06-13 19:30:16'
'7', '1',   '1319',  '2017-06-13 19:30:17'
'8', '1',   '1319',  '2017-06-13 19:30:18'
'9', '1',   '1319',  '2017-06-13 19:30:25'
'10','1',   '1319',  '2017-06-13 19:31:51'

我希望没有重复的item_ids,只有该项目的最新条目。 但我也想要所有报告,但没有重复的项目报告!

实施例: 我希望当我执行我的查询时,我只返回第2,4和10行。

4 个答案:

答案 0 :(得分:2)

试试这个:

select a.id,a.user,a.item_id,a.created
from reports as a
where a.created=(select max(created) 
                from reports as b
                where a.item_id=b.item_id)

答案 1 :(得分:0)

您可以使用group by:

SELECT * FROM t.reports WHERE created IN (SELECT max(created) FROM t.reports) 
GROUP BY item_id
LIMIT 100

答案 2 :(得分:0)

试试这个我在测试数据库上测试过它:

SELECT DISTINCT item_id, MAX(created), id, user
FROM `t.reports`
GROUP BY item_id
ORDER BY MAX(created) DESC

答案 3 :(得分:0)

试试这个让我知道这是否有效。

SELECT * 
FROM t.reports 
where item_id in (
                    select distinct item_id 
                    from t.reports
                ) 
ORDER BY updated DESC 
LIMIT 100