sql - 仅当 select 返回有效行时才从 select 插入表

标签 sql postgresql postgresql-9.1

我想从 select 语句插入到表中,但要求插入仅在 select 返回有效行时发生。如果没有行从 select 返回,则不会发生插入。

insert into products (name, type) select 'product_name', type from prototype where id = 1

但是,即使 select 没有返回任何行,上面的 sql 也会执行插入操作。 它会尝试插入 NULL 值。

我知道下面的sql可以检查行是否存在

select exists (select true from prototype where id = 1)

如何写一条SQL把上面的条件插入排除大小写?

最佳答案

你插入的方式不对。请参见下面的示例,它不会插入任何行,因为没有匹配 id = 1 的行:

create table products (
  name varchar(10),
  type varchar(10)
);

create table prototype (
  id int,
  name varchar(10),
  type varchar(10)
);

insert into prototype (id, name, type) values (5, 'product5', 'type5');  
insert into prototype (id, name, type) values (7, 'product7', 'type7');

insert into products (name, type) select name, type from prototype where id = 1
-- no rows were inserted.

关于sql - 仅当 select 返回有效行时才从 select 插入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532168/

相关文章:

sql - oracle中如何逐列比较两个表

PostgreSQL - 更新查询中的语法错误

postgresql - 如何计算 Postgres 使用 Knex 在查询中实际执行的时间

sql - 如果丢失,PostgreSQL 使用前一行的值

sql - 按名字和姓氏搜索的 Postgresql 查询,我应该创建哪些索引?

java - 中止插入...选择子句

postgresql-9.1 - postgresql - 选择西里尔文本(utf-8)时如何对齐列?

sql - 如何按 a、b 进行分组并返回 b 的 N 行集

javascript - 使用javascript从输入开始循环到结束日期

performance - PostgreSQL 查询未执行或花费太多时间