我想通过sql中的每个id_foreign获取最后的记录,例如我想要做的事情:
输入
id: 1, id_foreign: 5, value: 1
id: 2, id_foreign: 4, value: 2
id: 3, id_foreign: 4, value: 3
id: 4, id_foreign: 5, value: 4
id: 5, id_foreign: 5, value: 5
输出:
id: 3, id_foreign: 4, value: 3
id: 5, id_foreign: 5, value: 5
DISTINCT 怎么样?还有其他想法吗?了解我?
尝试了此解决方案:
SELECT * FROM table
GROUP BY id_foreign
ORDER BY id DESC
但输出我:
id: 1, id_foreign: 5, value: 1
id: 2, id_foreign: 4, value: 2
我同时尝试了(ASC和DESC)和输出错误。
答案 0 :(得分:2)
使用NOT EXISTS
:
SELECT *
FROM MyTable t
WHERE NOT EXISTS (
SELECT * FROM MyTable tt WHERE tt.id_foreign=t.id_foreign AND tt.id > t.id
)