我的表結構如本文所述:
name | version | processed | processing | updated | ref_time
------ --------- ----------- ------------ ---------- ----------
abc | 1 | t | f | 27794395 | 27794160
def | 1 | t | f | 27794395 | 27793440
ghi | 1 | t | f | 27794395 | 27793440
jkl | 1 | f | f | 27794395 | 27794160
mno | 1 | t | f | 27794395 | 27793440
pqr | 1 | f | t | 27794395 | 27794160
基于這個答案,我正在推匯出一個ref_time值串列,我想將其用作從 中洗掉“舊”條目的基礎status_table。
這是生成相關ref_time值串列的查詢:
WITH main AS
(
SELECT ref_time,
ROUND(AVG(processed::int) * 100, 1) percent
FROM status_table
GROUP BY ref_time ORDER BY ref_time DESC, percent DESC
)
SELECT ref_time FROM main WHERE percent=100 OFFSET 2;
例如,這可能會回傳:
ref_time
----------
27794880
27794160
然后我可以將它用于以下DELETE所有相關條目status_table:
DELETE FROM status_table
WHERE ref_time IN
(
WITH main AS
(
SELECT ref_time,
ROUND(AVG(processed::int) * 100, 1) percent
FROM status_table
GROUP BY ref_time ORDER BY ref_time DESC, percent DESC
)
SELECT ref_time FROM main WHERE percent=100 OFFSET 2
);
但是我有另一個名為的表data_table,它也有一ref_time列,我想DELETE在相同的基礎上從該表中輸入條目,即ref_time上面串列中的任何行。
如何在不復制用于生成ref_time串列的查詢的情況下實作這一點?
uj5u.com熱心網友回復:
您可以使用公用表運算式:
with
ref as (
select ref_time
from status_table
group by ref_time
having bool_and(processed)
order by ref_time desc limit 2
),
del_ref as (
delete from status_table s
using ref r
where s.ref_time = r.ref_time
)
delete from data_table d
using ref r
where d.ref_time = r.ref_time
第一個 CTEref回傳要從其他兩個表中洗掉的時間戳串列。我試圖簡化邏輯:您似乎想要完全處理的前 2 個時間戳(請注意,它會從結果集中offset 跳過那么多行,這與 不同limit)。
第二個 CTE 洗掉 fromstatus_table和查詢地址的最后一部分data_table。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528921.html
