gpt4 book ai didi

mysql根据select从一个表插入到另一个表

转载 作者:行者123 更新时间:2023-12-01 23:36:21 26 4
gpt4 key购买 nike

假设我们有

表A

field 1 | field 2

orange | fruit
apple | fruit

表B

field 1 | field 2

orange | fruit
lemon | fruit

并且只想将表 B 中与字段 1 不匹配的行插入到表 A 中,以便表 A 变为:

表A

field1  | field2

orange | fruit
apple | fruit
lemon | fruit

我试过了

insert into tableA (field1, field2)
select field1, field2 from tableB
where not exists
(select * from tableA as a join tableB as b on a.field1 = b.field1)

(无插入)

insert into tableA (field1, field2)
select field1, field2 from tableA as a left join tableB as b on a.field1 = b.field1
union
select field1, field2 from tableA as s right join tableB as b on a.field1 = b.field1
where a.field1 != b.field1

(插入不正确)

最佳答案

您的 NOT EXISTS 表达式不正确,它需要查看您尝试插入的 tableB 中的值:

INSERT INTO tableA (field1, field2)
SELECT field1, field2
FROM tableB b
WHERE NOT EXISTS (SELECT * FROM tableA a WHERE a.field1 = b.field1)

此查询后 SELECT * FROM tableA 的输出:

field1  field2
orange fruit
apple fruit
lemon fruit

Demo on db-fiddle

关于mysql根据select从一个表插入到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com