简体   繁体   English

从一个表中选择数据,然后插入到该表中不存在的另一个现有表中

[英]Select data from one table and insert into another existing table, which doesn't exist in the table

My table scheme is as follows: (Bold column name is primary key) 我的表方案如下:(粗体列名称是主键)

Table 1: id1 - id2 表1: ID1 -ID2

Table 2: id2 - name2 表2: id2 -name2

Table 3: id3 - name3 表3: id3 -name3

Table 4: id1 - Id3 表4:id1-id3

What I want to do is have sql code that : 我想要做的是具有以下代码:

  1. Select data in id1 and id3 columns for which name2=input=name3 在id1和id3列中选择name2 = input = name3的数据
  2. Insert into table 4 插入表4
  3. Only insert into 4 if id1, id3 combination doesn't exist in table 4 如果表4中不存在id1,id3组合,则仅插入4

Currently I can do step 1 and 2, but (assuming it can be done) I cannot get the syntax for "NOT EXIST" correct for step 3. 目前,我可以执行第1步和第2步,但是(假设可以完成)我无法获得第3步正确的“ NOT EXIST”语法。

This is my code currently: 这是我目前的代码:

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'

Here the query you need 在这里您需要查询

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
   )

as an advice - I suggest you always use aliases (and refer to column as alias.column_name ) in your queries, it'll help you to avoid bugs and your queries will be more readable. 作为建议-我建议您在查询中始终使用别名(并将列称为alias.column_name ),这将帮助您避免错误,并使查询更具可读性。

I think you are looking for this 我想你在找这个

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

or something similar. 或类似的东西。 Left (outer join) gets all the records in table2 whether they exist or not. 左(外部联接)获取表2中的所有记录,无论它们是否存在。 If they don't table3.name3 will be null, so those are the chaps you want. 如果不这样做,则table3.name3将为null,因此这些都是您想要的。

your current query is ok for the insertion, but if you want to deny inserts if that combination already exists, simply add a primary key to table4, that contains those 2 columns. 您当前的查询可以插入,但是如果要拒绝插入(如果该组合已经存在),则只需向table4添加一个包含这2列的主键。

In the query do: 在查询中执行:

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'
ON DUPLICATE KEY UPDATE id1=id1;

that is just for making the query still run, if there is a duplicate it will do nothing. 那只是为了使查询仍然运行,如果有重复,它将什么都不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM