仅当 select returns 有效行时才从 select 插入到 table

Insert into table from select only when select returns valid rows

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

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

但是,即使 select return 没有行,上面的 sql 也会插入。 它尝试插入 NULL 值。

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

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

如何写单SQL添加上面的条件插入排除大小写?

您插入的方式有误。请参见下面的示例,它不会插入任何行,因为 none 匹配 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.