【问题标题】:MYSQL Import Column from another table matching multiple columnsMYSQL 从另一个表中导入列匹配多个列
【发布时间】:2023-03-30 09:27:01
【问题描述】:

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

表一:

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

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

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

    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)。

    如果您不知道,您可以基于selects 构建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 示例。

    【讨论】:

    • 嗨 Kritner,这会将表 1 中的 NULL 值更新为表 2 中的代码 2 值吗?那是我希望通过的唯一专栏..
    • 上面不会更新任何东西它只是一个选择语句。
    • update 语句应该足够简单,可以基于 select 语句构建...见 stackoverflow.com/questions/1262786/…
    • @Kritner 更新的语法略有偏差。我可以得到你的编辑权限吗?
    • @Thomh 和 Kritner,我修复了更新语法并添加了一个 Fiddle(因为我正在测试它,没有必要给出第二个答案)。如果您希望仅更新表一中值为NULL 的位置,您只需将其添加到您的连接条件:ON t1.name = t2.name AND t1.code = t2.code AND t1.code2 IS NULL。请参阅 this Fiddle link 以获取由于不为空而未更新的行。
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多