如果表_A中不存在Table_B中的数据,我想将Table1中的一些数据从Table_B插入到Table_A中。例如,'Headache'位于Table_B的column1中,但不在Table_A的column1中。谢谢。我在下面编写了SQL,但它不起作用:
insert into Table_A(column1)
select column1
from Table_B
where column1 not in (select column1 from Table_A)
答案 0 :(得分:1)
试试这个:
INSERT INTO Table_A(column1)
SELECT B.column1
FROM Table_B B
LEFT JOIN Table_A A ON B.column1 = A.column1
WHERE A.column1 IS NULL
答案 1 :(得分:0)
Insert into Table_A(column1)
select column1 from Table_B
left join Table_A on Table_B.column1 = Table_A.column1
where A.column1 is null
答案 2 :(得分:0)
没有样本数据很难肯定,但我最好的猜测是NULL
中有table_A.Column1
值。如果你确实有一个空值,你的查询将等同于:
SELECT Column1
FROM Table_B
WHERE Column1 NOT IN (1, 2, 3, NULL);
相当于:
SELECT Column1
FROM Table_B
WHERE Column1 <> 1
AND Column1 <> 2
AND Column1 <> 3
AND Column1 <> NULL;
由于Column1 <> NULL
不成立,查询不返回任何结果。在您可能具有NULL列的情况下,实现所需结果的语法最相似的方法是使用NOT EXISTS
:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
WHERE NOT EXISTS (SELECT 1 FROM Table_A AS A WHERE A.Column1 = B.Column1);
但是,您可以使用的另一种方法是:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
LEFT JOIN Table_A AS A
ON A.Column1 = B.Column1
WHERE A.Column1 IS NULL;
通过左侧加入table_A
然后声明A.Column1
必须为NULL
,您将删除Table_A
中已存在的所有记录。
我更喜欢前者(NOT EXISTS
),因为我觉得意图更清晰,但如果你use MySQL the latter will perform better
或者您也可以使用:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
WHERE B.Column1 IS NOT NULL
AND B.COlumn1 NOT IN (SELECT A.Column1 FROM Table_A AS A WHERE A.Column1 IS NOT NULL);
答案 3 :(得分:0)
使用MERGE语句怎么样?
MERGE INTO TABLE_A a
USING TABLE_B b ON (a.column1=b.column1)
WHEN NOT MATCHED THEN
INSERT (column1) VALUES (b.column1);