简体   繁体   English

MySQL从其他表插入一个表列

[英]MySQL-insert into one table columns from other tables

I need to copy two columns from two different tables into new table: 我需要将两个不同表中的两列复制到新表中:

t1: col1  col2       t2: col3  col4
    a1     b1              c1   d1
    a2     b2              c2   d2
                           c3   d3

I need to get this: 我需要得到这个:

t3: col1  col4
     a1    d1
     a2    d2
     null  d3

I used query: 我用查询:

INSERT INTO t3 (col1,col4) SELECT t1.col1, t2.col4 FROM t1,t2

but i am getting this: 但我得到这个:

t3: col1  col4
     a1    d1
     a2    d1
     a1    d2
     a2    d2
     a1    d3
     a2    d3

Can anyone help? 有人可以帮忙吗? Should I use some other query? 我应该使用其他查询吗? Tnx! TNX!

You are using a CROSS JOIN , or carthesian product. 您正在使用CROSS JOIN或笛卡尔积。 This means that all rows in the left table will match all rows in the right table. 这意味着左表中的所有行将与右表中的所有行匹配。 This happens because you didn't tell MySQL how the tables rows should match. 发生这种情况是因为您没有告诉MySQL表行应如何匹配。

You need to add the JOIN keyword and specify an ON clause, which specifies the matching rule - which values must be equal. 您需要添加JOIN关键字并指定ON子句,该子句指定匹配的规则-值必须相等。 For example: 例如:

SELECT a.col1, b.col4 FROM t1 a INNER JOIN t2 b ON a.id_t2 = b.id;

To be able to retrieve the above result, you'll need to use the left outer join , but however I can't find any linking columns. 为了能够检索上述结果,您需要使用left outer join ,但是我找不到任何链接列。

 between your two tables;

INSERT INTO t3 (t1.col1,t2.col4) 
SELECT t1.col1, t2.col4 
FROM t2
Left Outer Join t1
on --> Your link column between the tables

It appears that your simply attempting to join the first row in one table to the first row in another table, then insert them into a third table. 看来您只是尝试将一个表中的第一行连接到另一个表中的第一行,然后将它们插入到第三张表中。 This SQL should perform the inserts: 此SQL应该执行插入:

insert into table3
  select col1, col4 from (select @rownum2 := @rownum2+1 as rown, col4 from table2
     JOIN (SELECT @rownum2 := 0) r2) t2
  left outer join
    (
    select @rownum := @rownum+1 as rown, col1 from table1
    JOIN (SELECT @rownum := 0) r) t1 
  on t2.rown = t1.rown;

SQL Fiddle: http://sqlfiddle.com/#!2/f9314f SQL小提琴: http ://sqlfiddle.com/#!2 / f9314f

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

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