我正在使用 PostgreSQL,并正在尋找一種在單個查詢中更新多條記錄的方法。我找到了這個解決方案:使用 PostgreSQL 在同一個查詢中更新多行
但是,當所有要更新的行都應使用 NULL 值更新時,此解決方案不起作用。這是一個例子:
表定義
create table person (id char(1), my_value smallint);
填充
insert into person values
('1', 1),
('2', NULL),
('3', 3)
;
不作業更新
update person as db_record_to_update set
my_value = db_record_new.my_value
from (values
('1', NULL),
('2', NULL)
) as db_record_new(id, my_value)
where db_record_new.id = db_record_to_update.id;
我得到的錯誤
DatatypeMismatch: column "my_value" is of type smallint but expression is of type text
LINE 3: my_value = db_record_new.my_value
^
HINT: You will need to rewrite or cast the expression.
問題
如何使用一個/多個欄位都為 null 執行多個更新?
筆記
- 僅當至少一個 my_value 不為空時,查詢才有效并且作業正常。例如,此查詢作業正常(我將 1 NULL 替換為 55 的相同 expet):
update person as db_record_to_update set
my_value = db_record_new.my_value
from (values
('1', NULL),
('2', 55)
) as db_record_new(id, my_value)
where db_record_new.id = db_record_to_update.id;
- 我在帶有psychog2的筆記本上運行這個查詢,以防萬一
uj5u.com熱心網友回復:
問題是 Postgres 不知道運算式中my_value列的型別VALUES,因此默認它們為text. NULL您可以通過使用所需型別注釋至少一個值來避免這種情況smallint:
update person as db_record_to_update
set my_value = db_record_new.my_value
from (values
('1', NULL::smallint),
('2', NULL)
) as db_record_new(id, my_value)
where db_record_new.id = db_record_to_update.id;
(在線演示)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/410436.html
標籤:
