如何在Postgres中进行这样的查询?
IF (select count(*) from orders) > 0 THEN DELETE from orders ELSE INSERT INTO orders values (1,2,3);
尝试:
原文链接:https://www.f2er.com/postgresql/192222.htmlDO $do$ BEGIN IF EXISTS (SELECT 1 FROM orders) THEN DELETE FROM orders; ELSE INSERT INTO orders VALUES (1,3); END IF; END $do$
要点
>标准sql中没有程序元素. IF
statement是默认的程序语言PL / pgsql的一部分.您需要使用DO
命令创建一个函数或执行一个ad-hoc语句.
>你需要一个在每个语句的末尾在plpgsql(except for the final END
).
>你需要END IF;在IF声明的结尾.
>子选择需要用括号括起来:
IF (SELECT count(*) FROM orders) > 0 ...
要么:
IF (SELECT count(*) > 0 FROM orders) ...
尽管如此,这是相当的,快得多:
IF EXISTS (SELECT 1 FROM orders) ...
替代
你根本不需要额外的SELECT.这样做也一样,有点快:
DO $do$ BEGIN DELETE FROM orders; IF NOT FOUND THEN INSERT INTO orders VALUES (1,3); END IF; END $do$