在 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中文网其他相关文章!