简体   繁体   中英

SQL join table with same column name

I want to join two tables with the same column names and update it using by ID (unique key)

表结构

I think that this may help you.....

The query uses the inner join to join the table1 and table2

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

With your Example:

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      |
+------+------+------+--------+

After the Update Query:

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

RESULT:

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

Used left join to join the tables. Try this code:-

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

也尝试一下:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM