我有一个包含以下语法的表:
ID, VALUE, TIMESTAMP
(ID,TIMESTAMP)
是主键,因此每个ID可能有多行。有5000个独特的ID。
我想检索每个ID的最新条目。
我天真的做法是:
SELECT * FROM table ORDER BY TIMESTAMP DESC LIMIT 5000;
对于大多数情况,这将给出正确的结果,但不能保证。
因为表中可能有100k到500k条目,所以我想考虑性能。
你有什么建议?
答案 0 :(得分:1)
尝试这个
SELECT ID, VALUE, TIMESTAMP
FROM table
GROUP BY ID
HAVING MAX(TIMESTAMP)
ORDER BY TIMESTAMP DESC ;
OR
SELECT ID, VALUE, TIMESTAMP
FROM table
GROUP BY ID
ORDER BY TIMESTAMP DESC ;
答案 1 :(得分:0)
你会找到每个ID条目的最新日期,试试这个
SELECT *
FROM table AS a
WHERE TIMESTAMP = (
SELECT MAX(TIMESTAMP)
FROM table AS b
WHERE a.ID = b.ID
)
答案 2 :(得分:0)
Please try this :
SELECT * FROM
(SELECT ID,
VALUE,
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY TIMESTAMP DESC) AS TIMESTAMP
FROM
TABLE )
WHERE TIMESTAMP=1 ;
If your DB supports QUALIFY statement you can try below also :
SELECT * FROM
TABLE
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY TIMESTAMP DESC)=1 ;`enter code here`