我想从 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/