gpt4 book ai didi

sql - 如何使 SQL JOIN 仅返回具有最新状态代码的一行?

转载 作者:行者123 更新时间:2023-12-03 16:50:28 29 4
gpt4 key购买 nike

以下 SQL 语句:

SELECT f.id, 
f.front,
f.back,
h.statusChangedIdCode,
h.whenCreated,
h.historyIdCode
FROM dpod_site_flashcards AS f
JOIN dpod_site_historyItems AS h ON f.id = h.itemId
WHERE f.id = 216
AND historyIdCode = 'statusChanged'
ORDER BY h.whenCreated

给我以下输出。 如何更改它以使其仅返回具有最新 statusChangedIdCode 的一行?

enter image description here

最佳答案

SELECT f.id, 
f.front,
f.back,
h.statusChangedIdCode,
h.whenCreated,
h.historyIdCode
FROM dpod_site_flashcards AS f
JOIN dpod_site_historyItems AS h ON f.id = h.itemId
WHERE f.id = 216
AND h.historyIdCode = 'statusChanged'
AND h.whenCreated = (select max(whenCreated)
from dpod_site_historyItems h2
where h2.itemId = h.itemId
and h2.historyIdCode = 'statusChanged')
ORDER BY h.whenCreated

或者,如果您有支持窗口功能的现代 DBMS:
SELECT f.id, 
f.front,
f.back,
h.statusChangedIdCode,
h.whenCreated,
h.historyIdCode
FROM dpod_site_flashcards AS f
JOIN (
select itemid,
historyIdCode,
whenCreated,
statusChangedIdCode,
row_number() over (partition by itemid order by whenCreated desc) as rn
from dpod_site_historyItems
where historyIdCode = 'statusChanged'
) h ON f.id = h.itemId AND h.rn = 1
WHERE f.id = 216
ORDER BY h.whenCreated

当您为多个 dpod_site_flashcards.id 选择行时,这两种情况也适用LIMIT 解决方案不会这样做。

关于sql - 如何使 SQL JOIN 仅返回具有最新状态代码的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14246028/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com