当 select 不匹配时插入

insert into when select not matching

我有这个问题:

INSERT INTO tbl_1(id , name)
SELECT  id, 'XXX' 
FROM tbl_2 t WHERE t.name='XXX';

它在 SELECT 子句匹配时起作用。即使 SELECT 不匹配,我也想在 "id" 字段中使用 0 执行插入查询。

将您的查询包含在子选择中(因此它总是 return 至少一个值):

INSERT INTO tbl_1(id , name)
SELECT COALESCE((SELECT id FROM tbl_2 t WHERE t.name='XXX'), 0), 'XXX';

INSERT INTO tbl_1(id , name)
SELECT COALESCE((SELECT id FROM tbl_2 t WHERE t.name=v.name), 0), v.name
FROM (VALUES ('XXX')) v(name);

您可以使用 UNION,其优点是 "base" select 返回的行数不限于一个:

INSERT INTO tbl_1 (id , name)
SELECT id, 'XXX' 
FROM tbl_2 t 
WHERE t.name='XXX'
union all
select 0, 'XXX'
where not exists (select 1 from tbl_2 t where t.name = 'XXX');