gpt4 book ai didi

mysql - 从一个表中选择数据并插入到另一个现有表中,该表中不存在

转载 作者:可可西里 更新时间:2023-11-01 06:50:02 26 4
gpt4 key购买 nike

我的表方案如下:(粗体列名为主键)

表 1:id1 - id2

表 2:id2 - name2

表 3:id3 - name3

表 4:id1 - Id3

我想做的是拥有这样的 sql 代码:

  1. 选择 id1 和 id3 列中的数据,其中 name2=input=name3
  2. 插入表 4
  3. 只有表4中不存在id1,id3组合才插入到4中

目前我可以执行第 1 步和第 2 步,但是(假设可以完成)我无法为第 3 步获得正确的“NOT EXIST”语法。

这是我目前的代码:

INSERT INTO table4( id1, id3) 
SELECT id1, id3
FROM table2
INNER JOIN table1 ON table1.id2 = table2.id2
INNER JOIN table3 ON table2.name2 = table3.name3
WHERE name2 LIKE 'input'

最佳答案

这里是你需要的查询

insert into table4(id1, id3) 
select t1.id1, t3.id3
from table2 as t2
inner join table1 as t1 on t1.id2 = t2.id2
inner join table3 as t2 on t2.name2 = t3.name3
where
t2.name2 like 'input' and
not exists (
select *
from table4 as t4
where t4.id1 = t1.id1 and t4.id3 = t3.id3
)

作为建议 - 我建议您在查询中始终使用别名(并将列称为 alias.column_name),这将帮助您避免错误,并且您的查询将更具可读性。

关于mysql - 从一个表中选择数据并插入到另一个现有表中,该表中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18035426/

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