我有以下幾點:
id int GENERATED ALWAYS AS IDENTITY,
ts timestamp WITHOUT TIME ZONE NOT NULL,
urgent bool NOT NULL,
origin varchar NOT NULL,
message varchar NOT NULL,
ts_read timestamp WITHOUT TIME ZONE
CREATE INDEX IF NOT EXISTS idx_alerts ON {accountId}.{tableAlertsName} (ts_read) WHERE ts_read IS NULL;
CREATE OR REPLACE VIEW {accountId}.pending_alerts AS
SELECT id, ts, level, origin, message from {accountId}.{tableAlertsName}
WHERE ts_read IS NULL ORDER BY urgent DESC, ts ASC;"
我想用一個級別列替換緊急列,該列將有幾個選項,例如info、warning、error等。
但在我看來,我想實作以下排序操作:
如果級別 = 警告或級別 = 錯誤,則首先添加這些,如果沒有,則按時間戳對其余部分進行排序。
我怎樣才能實作這種排序操作?
uj5u.com熱心網友回復:
您可以對視圖使用 union all,第一個查詢將用于級別上的 where 子句,第二個查詢將用于時間戳的 order by。
創建或替換視圖 {accountId}.pending_alerts AS SELECT id, ts, level, origin, message from {accountId}.{tableAlertsName} WHERE (ts_read IS NULL AND (level = warning or level = error)) UNION ALL (SELECT id, ts, level, origin, message from {accountId}.{tableAlertsName} WHERE ts_read IS NULL ORDER BY Emergency DESC, ts ASC)
View 的性能可能代價高昂,您可以使用函式來創建類似的場景。
CREATE OR REPLACE FUNCTION pending_alerts () RETURNS TABLE(id int, .....) AS $$ BEGIN RETURN QUERY SELECT id, ts, level, origin, message from {accountId}.{tableAlertsName} WHERE (ts_read IS NULL AND (級別 = 警告或級別 = 錯誤)) UNION ALL (SELECT id, ts, level, origin, message from {accountId}.{tableAlertsName} WHERE ts_read IS NULL ORDER BY Emergency DESC, ts ASC); 結尾; $$ 語言 plpgsql;
uj5u.com熱心網友回復:
警告和錯誤應該相互聯系還是分開?如果它們被綁在一起:
ORDER BY (level = 'warning' or level = 'error') DESC, ts ASC
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/317116.html
標籤:PostgreSQL
上一篇:RobotFramework:通過SSH隧道連接PostgreSQL資料庫
下一篇:JOIN查詢的行估計
