我的表方案如下:(粗体列名为主键)
表 1:id1 - id2
表 2:id2 - name2
表 3:id3 - name3
表 4:id1 - Id3
我想做的是拥有这样的 sql 代码:
- 选择 id1 和 id3 列中的数据,其中 name2=input=name3
- 插入表 4
- 只有表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/