在 PostgreSQL 中,同時更新多行在處理 NULL 值時可能會遇到挑戰。當使用獨立的 VALUES 表達式時,PostgreSQL 缺乏有關資料類型的信息。因此,非數字文字(包括 NULL 值)需要明確轉換。
要解決此問題,請探索以下解決方案:
UPDATE foo SET x=t.x, y=t.y FROM ( (SELECT pkid, x, y FROM foo LIMIT 0) UNION ALL VALUES (1, 20, NULL) -- no type casts here , (2, 50, NULL) ) t -- column names and types are already defined WHERE f.pkid = t.pkid;
UPDATE foo SET x=t.x, y=t.y FROM ( (SELECT pkid, x, y FROM foo LIMIT 0) UNION ALL SELECT 1, 20, NULL UNION ALL SELECT 2, 50, NULL ) t -- column names and types are already defined WHERE f.pkid = t.pkid;
... FROM ( VALUES ((SELECT pkid FROM foo LIMIT 0) , (SELECT x FROM foo LIMIT 0) , (SELECT y FROM foo LIMIT 0)) -- get type for each col individually , (1, 20, NULL) , (2, 50, NULL) ) t (pkid, x, y) -- columns names not defined yet, only types. ...
UPDATE foo f SET x = (t.r).x -- parenthesis needed to make syntax unambiguous , y = (t.r).y FROM ( VALUES ('(1,20,)'::foo) -- columns need to be in default order of table ,('(2,50,)') -- nothing after the last comma for NULL ) t (r) -- column name for row type WHERE f.pkid = (t.r).pkid;
... FROM ( VALUES ((NULL::foo).*) -- decomposed row of values , (1, 20, NULL) -- uniform syntax for all , (2, 50, NULL) ) t(pkid, x, y) -- arbitrary column names (I made them match) ...
以上是如何在 PostgreSQL 中高效更新多行 NULL 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!