[英]MySQL-insert into one table columns from other tables
我需要將兩個不同表中的兩列復制到新表中:
t1: col1 col2 t2: col3 col4
a1 b1 c1 d1
a2 b2 c2 d2
c3 d3
我需要得到這個:
t3: col1 col4
a1 d1
a2 d2
null d3
我用查詢:
INSERT INTO t3 (col1,col4) SELECT t1.col1, t2.col4 FROM t1,t2
但我得到這個:
t3: col1 col4
a1 d1
a2 d1
a1 d2
a2 d2
a1 d3
a2 d3
有人可以幫忙嗎? 我應該使用其他查詢嗎? TNX!
您正在使用CROSS JOIN
或笛卡爾積。 這意味着左表中的所有行將與右表中的所有行匹配。 發生這種情況是因為您沒有告訴MySQL表行應如何匹配。
您需要添加JOIN
關鍵字並指定ON子句,該子句指定匹配的規則-值必須相等。 例如:
SELECT a.col1, b.col4 FROM t1 a INNER JOIN t2 b ON a.id_t2 = b.id;
為了能夠檢索上述結果,您需要使用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
看來您只是嘗試將一個表中的第一行連接到另一個表中的第一行,然后將它們插入到第三張表中。 此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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.