我有两张表,其中一张是这样的:
表 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 中的代码 # 列。为此,我需要匹配名称和代码列,以将“代码 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
最佳答案
您可以同时连接多个列上的表,例如:
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”匹配,因为仅在两个表之间的名称和代码相等的情况下才执行联接。 (注意约翰 452 也将加入约翰 452)。
如果您不知道,您可以基于 select
构建 update
语句。您的更新语句最终看起来像这样:
update t1
inner join t2 on t1.name = t2.name and t1.code = t2.code
set t1.code2 = t2.code2;
这将连接名称和代码匹配的两个表,并将第一个表中的 code2 设置为等于第二个表中的 code2。
这是一个SQL Fiddle示例。
关于MYSQL从匹配多个列的另一个表导入列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611194/