2017-06-14 60 views
1

我只想得到所有项目的最后报告,但只有最近的报告为每个item_id。 这是我目前的解决方案:如何删除我的SQL结果中最旧的条目?

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返回。

+0

'DISTINCT *'是自相矛盾 – Strawberry

+2

我想你需要给我们你想要什么更具体的解释。也许有一些例子 – RiggsFolly

+0

检查我更新的q。 –

回答

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) 
+0

谢谢!这工作正如我想要的! :) –

+0

你介意解释SQL,以便我更好地理解它吗? –

+0

@Oliver Hoff,你需要最新的报告,所以你要做的第一件事就是寻找每个item_id的最高日期(创建),这就是你在子查询中所做的。一旦你知道最大日期,你只需选择与该日期相对应的报告 – nacho

0

您可以通过使用组:

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

这不起作用,它会返回来自数据库的第一个日期具有相同的'item_id'它不会找到最新日期 –

0

这个我已经测试过它在我的测试数据库尝试:

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

无效GROUP BY https://www.psce.com/blog/2012/05/15/mysql-错误 - 你使用小组 - 正确/ –

0

试试这个让我知道,如果这个工程。

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