我想从select语句插入表中,但是要求插入仅在select返回有效行时发生。如果没有从选择返回的行,则不会发生插入。
insert into products (name, type) select 'product_name', type from prototype where id = 1
但是,即使选择不返回任何行,上述sql也会插入。 它尝试插入NULL值。
我知道以下sql可以检查行是否存在
select exists (select true from prototype where id = 1)
如何编写单个SQL以添加上述条件以插入以排除大小写?
答案 0 :(得分:1)
您插入的方式错误。请参见下面的示例,该示例不插入任何行,因为没有一个匹配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.