MYSQL从另一个表中匹配多列的导入列

时间:2015-07-24 12:59:52

标签: mysql sql

我有两张桌子,其中一张是这样的:

表1:

ID- Name-   Code-   Code 2-

1-  John-   115-null    
2-  Rick-   652-null    
3-  Jones-  886-null    
4-  James-  554-null    
5-  Elton-  125-null    
6-  Craig-  214-null    
7-  John-   452-null    

表2:

Name-   Code-   Code 2- 

John-   115-    a   
Rick-   652-    b   
Jones-  886-    c   
James-  554-    d   
Elton-  125-    e   
Craig-  214-    f   
John-   452-    g   
Craig-  886-    h   
Rick-   115-    i   

这不是真正的数据,它并不那么简单。我需要将表2中的代码2放入表1中的Code#列。为此,我需要将Name和Code列匹配,以从Column' Code 2'中获取数据。进入专栏'代码#'。它需要匹配至少两列,因为每个列都有重复...

我想最终得到类似的东西:

ID- Name-   Code-   Code 2-

1-  John-   115-a   
2-  Rick-   652-b   
3-  Jones-  886-c   
4-  James-  554-d   
5-  Elton-  125-e   
6-  Craig-  214-f   
7-  John-   452-g

1 个答案:

答案 0 :(得分:4)

您可以一次连接多个列上的表格,如:

select t1.id, t1.name, t1.code, t2.code2
from t1
inner join t2 on t1.name = t2.name
    and t1.code = t2.code

这种方式(来自您的示例)“John 115”将仅与“John 115”而不是“John 452”匹配,因为仅在两个表之间的名称和代码相等的情况下执行连接。 (注意John 452也将加入John 452)。

如果您不知道,可以根据update构建select语句。您的更新语句最终会看起来像这样:

update t1
inner join t2 on t1.name = t2.name and t1.code = t2.code
set t1.code2 = t2.code2;

这将连接名称和代码匹配的两个表,并将第一个表中的code2设置为等于第二个表中的code2。

以下是SQL Fiddle示例。

相关问题