具有相同列名的SQL连接表

时间:2017-02-08 06:41:07

标签: mysql sql

我想连接两个具有相同列名的表,并使用ID(唯一键)

进行更新

table structure

4 个答案:

答案 0 :(得分:0)

我认为这可能会对你有帮助.....

查询使用内部联接来连接table1和table2

SELECT T1.name1,T2.name2
FROM `table1` T1 
INNER JOIN `table2` T2 ON t2.name1=t1.PrimaryKey;

答案 1 :(得分:0)

使用您的示例:

select * from Table1;
+----+------+------+--------+
| ID | Name | age  | Gender |
+----+------+------+--------+
|  1 | Pars |   23 | M      |
|  2 | Pepe |   24 | M      |
|  3 | Pio  |   25 | M      |
|  4 | Pak  |   26 | F      |
+----+------+------+--------+

select * from Table2;
+------+------+------+--------+
| ID   | Name | age  | Gender |
+------+------+------+--------+
|    1 | Pars |   30 | M      |
|    2 | Pepe |   31 | M      |
|    3 | Pio  |   32 | M      |
+------+------+------+--------+

更新查询后:

Update Table1 join Table2 using(ID) set Table1.AGE=Table2.AGE;

结果:

select * from Table1;
+----+------+------+--------+
| ID | Name | age  | Gender |
+----+------+------+--------+
|  1 | Pars |   30 | M      |
|  2 | Pepe |   31 | M      |
|  3 | Pio  |   32 | M      |
|  4 | Pak  |   26 | F      |
+----+------+------+--------+

答案 2 :(得分:0)

使用左连接来连接表。 试试这个代码: -

select a.id ,
       coalesce(a.name,b.name) as name
      ,coalesce(b.age,a.age)as age
      ,coalesce(a.gender,a.gender)as gender
from table1 as a
left join Table2 as b 
on a.id=b.id

答案 3 :(得分:0)

也可以尝试:

update Table1 set Table1.age=Table2.age from table1 inner join table2 on Table1.id=Table2.id