嗨,我有一个查询,它返回一个表中存在但在另一个表中不存在的客户列表。对于每个返回的customer_id,我需要在profile表中添加2行。
如何在sql中编写这两行的插入语句?
select * FROM
(select *
from customer c
left outer join profile cp
on cp.customer_id=c.global_id
order by c.global_id) as A
where id is NULL;谢谢!
发布于 2014-11-28 05:44:34
一种选择是使用cross join创建cartesian product
insert into profile (customerid ...)
select customerid ...
FROM
(select *
from customer c
left outer join profile cp
on cp.customer_id=c.global_id
) as A cross join (SELECT 1 col UNION SELECT 2) as B
where id is NULL;发布于 2014-11-28 06:13:46
对于少量行,CROSS JOIN (与FROM列表中的,相同)到表达式是最短、最简单的方法:
INSERT INTO profile (<list of columns>)
SELECT <list of columns>
FROM (
SELECT <list of columns>
FROM customer c
LEFT JOIN profile p ON p.customer_id = c.global_id
WHERE p.customer_id IS NULL
) A
, (VALUES (1), (2)) dummy(col_name)
ORDER BY global_id;在SELECT和INSERT中使用显式列列表,以避免在以后更改任何内容时出现意外结果。
您可能不会对两个相同的行执行INSERT操作。您可以立即在子查询dummy中提供有用的值。可能使用显式类型转换。像这样:
(VALUES ('foo'::text), ('bar')) dummy(col_name)https://stackoverflow.com/questions/27178781
复制相似问题