Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从subselect PostgreSQL中插入大小写表达式_Sql_Postgresql_Insert_Case - Fatal编程技术网

从subselect PostgreSQL中插入大小写表达式

从subselect PostgreSQL中插入大小写表达式,sql,postgresql,insert,case,Sql,Postgresql,Insert,Case,我正在尝试创建这样一个查询 WITH insert1 as (), ... subselect1 as (SELECT (CASE WHEN %s is NOT NULL THEN (INSERT INTO Duration (duration) VALUES (ROW (%s, %s)) RETURNING id as id_duration) ELSE (INSERT INTO Distance (leng

我正在尝试创建这样一个查询

WITH insert1 as (),
...
subselect1 as (SELECT
   (CASE
     WHEN %s is NOT NULL THEN
          (INSERT INTO Duration (duration)
          VALUES (ROW (%s, %s)) RETURNING id as id_duration)
     ELSE
          (INSERT INTO Distance (length)
          VALUES (ROW (%s, %s)) RETURNING id as id_distance)
       END)),
...
INSERT INTO FinalTable...
我知道我的语法有问题。您是否通过使用Insert into来完成此操作

我的计划是: 通过一个WITH语句,使用返回值进行多次插入,最后插入到FinalTable。只有插入值和返回值,效果很好-我必须在FinalTable中引用它们,例如(
从insert3中选择id\u点)

但是这个例子-我想从insert返回值,用case包装(%s表示参数化查询,从python传递变量)。因此,如果第一个%s不是NULL,我必须插入到表的持续时间,否则我必须插入到表的距离

在FinalTable中插入时,我有对这些表的引用(列idDistance,idDuration)-因此我想写smth,比如(…,(
从子选择1选择id\u duration),(
从子选择1选择id\u distance
)…)


我的语法出了什么问题?

我不清楚您想要实现什么,但也许您正在寻找类似的东西:

WITH insert1 as (
...
),
insert_duration (id_duration) as (
  insert into duration (duration, ....) 
  select .... 
  from (
      values (..),(..)
  ) as t(...)
  where $1 IS NOT NULL --<< first branch of your CASE expression
  returning id
), 
insert_distance (id_distance) as (
  insert into distance (length, ...) 
  select .... 
  from (
      values (..),(..)
  ) as t(...)
  where $1 IS NULL --<< ELSE branch of your CASE expression
  returning id
)
INSERT INTO final_table 
...
将insert1作为(
...
),
插入\u持续时间(id\u持续时间)作为(
插入持续时间(持续时间,…)
选择。。。。
从(
值(…),(…)
)as t(…)

其中$1不为空——您不能在大小写表达式中使用
INSERT
。@一个没有名字的马,请您评论
PL/pgSQL
大小写和
SQL
大小写不是一回事。这个问题的解决方案是使用PL/pgSQL
CASE
,而您使用的是SQL
CASE
插入到单个列中n使用
row()
构造对我来说似乎非常奇怪。谢谢你的回答!似乎你的想法不适合我的情况-我想根据Python脚本中传递的变量值(如果为NULL,则无需插入,否则插入)将插入分为表(持续时间、距离)。因此,我没有选择(在分支中),因为它只是values@Jane:这仍然有效,请参阅我的编辑。您可以从要插入的值中“选择”如果我必须插入一个值数组(我需要检查数组是否存在)-从值中选择..(unest(array))它会抛出一个错误
设置值中不允许返回函数
…您的建议是什么?)