问题
I want to get only the last reports, for all items but only the most recent report for each item_id.
Here is my current solution:
SELECT distinct * FROM t.reports ORDER BY created DESC LIMIT 100
My table consists of the following columns:
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'
I want no duplicate item_ids AND only the most recent entry for that item. BUT i also want ALL reports, but no duplicate item reports!
EXAMPLE: i expect that when i execute my query, i only get row 2,4 and 10 returned.
回答1:
Try this:
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)
回答2:
Try This let me know if this works.
SELECT *
FROM t.reports
where item_id in (
select distinct item_id
from t.reports
)
ORDER BY updated DESC
LIMIT 100
回答3:
Try with this I have tested it on my test database:
SELECT DISTINCT item_id, MAX(created), id, user
FROM `t.reports`
GROUP BY item_id
ORDER BY MAX(created) DESC
回答4:
You can use group by :
SELECT * FROM t.reports WHERE created IN (SELECT max(created) FROM t.reports)
GROUP BY item_id
LIMIT 100
来源:https://stackoverflow.com/questions/44543764/how-can-i-remove-the-oldest-entries-in-my-sql-result