[英]Finding updates in a table using Self-Join
我有一張桌子,如下所示
表名-屬性
|runId|listingId|listingName 1 123 abc 1 234 def 2 123 abcd 2 567 ghi 2 234 defg
如您在上面的代碼中看到的,有一個runId和一個列表ID。 我正在嘗試獲取特定的runId,這些runId是添加的新列表(在這種情況下,對於runId 2,其第4行的列表ID為567),並且是要更新的列表ID(在此情況下,其id的第3行和第5行listingId 123和234)
我正在嘗試自我加入,它正在為新的更新工作,但是新的添加給我帶來了麻煩
SELECT p1.* FROM property p1 INNER JOIN property p2 ON p1.listingid = p2.listingid WHERE p1.runid=456 AND p2.runid!=456
上面的查詢為我提供了表中正確的更新記錄。 但是我找不到新的清單。 我用了p1.listingid!= p2.listingId,左外連接,仍然無法正常工作。
您可以嘗試一下。
with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property
)
select * from property where listingId not in (
select listingId from cte as c where slno>1
) --- for new listing added
with cte as (
select row_number() over (partition by listingId order by runId) as Slno, * from property
)
select * from property where listingId in (
select listingId from cte as c where slno>1
) --- for modified listing
我將使用ROW_NUMBER()
分析函數。
SELECT
T.*
FROM
(
SELECT
T.*,
CASE
WHEN ROW_NUMBER() OVER(
PARTITION BY LISTINGID
ORDER BY
RUNID
) = 1 THEN 'INSERTED'
ELSE 'UPDATED'
END AS OPERATION_
FROM
PROPERTY
)
WHERE
RUNID = 2
-- AND OPERATION_ = 'INSERTED'
-- AND OPERATION_ = 'UPDATED'
如果在以前的任何runid
添加了listingid
這將提供更新后的結果
干杯!!
為此,我建議exists
和not exists
。 有關更新:
select p.*
from property p
where exists (select 1
from property p2
where p2.listingid = p.listingid and
p2.runid < p.runid
);
如果您想要特定runid
的結果,請添加and runid = ?
到外部查詢。
對於新列表:
select p.*
from property p
where not exists (select 1
from property p2
where p2.listingid = p.listingid and
p2.runid < p.runid
);
使用property(listingid, runid)
的索引,我希望它比使用窗口函數的解決方案具有更好的性能。
這是db <>小提琴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.