2017-06-14 36 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