在第三个表中组合2个mysql表

时间:2017-05-05 06:29:33

标签: mysql sql database

我在mySql中有3个表==> tableA,tableB,tableC

在tableA中,我有以下

+---------+----+----+--------+------------+--+
|  Name   | N1 | N2 | Color  |   State    |  |
+---------+----+----+--------+------------+--+
| John    | 60 | 50 | Red    | Newyork    |  |
| Tom     | 70 | 60 | Green  | Kansas     |  |
| Mathew  | 50 | 40 | Blue   | Texas      |  |
| James   | 40 | 30 | Yellow | Texas      |  |
| SSS     | 70 | 60 | Pink   | Washington |  |
+---------+----+----+--------+------------+--+

在表B中,我有以下

+--------+----+----+
| S.Name | N3 | N4 |
+--------+----+----+
| Carl   | 10 | 18 |
| Jason  | 15 |  9 |
| Cindy  | 13 | 12 |
| Tim    |  7 | 18 |
| Pam    | 15 | 14 |
+--------+----+----+

在表C中,我想要以下

+---------+----+----+--------+------------+--------+
|  Name   | N1 | N2 | Color  |   State    | S.Name |
+---------+----+----+--------+------------+--------+
| John    | 60 | 50 | Red    | Newyork    |        |
| Tom     | 70 | 60 | Green  | Kansas     |        |
| Mathew  | 50 | 40 | Blue   | Texas      |        |
| James   | 40 | 30 | Yellow | Texas      |        |
| SSS     | 70 | 60 | Pink   | Washington |        |
|         | 10 | 18 |        |            | Carl   |
|         | 15 |  9 |        |            | Jason  |
|         | 13 | 12 |        |            | Cindy  |
|         |  7 | 18 |        |            | Tim    |
|         | 15 | 14 |        |            | Pam    |
+---------+----+----+--------+------------+--------+

请帮我这个SQL查询。感谢

4 个答案:

答案 0 :(得分:3)

作为选择结果,您可以使用简单的union all: 选择Name作为Name,N1作为N1,N2作为N2,Color作为Color,State作为State,null作为来自tableA的S_Name 联合所有 选择null作为Name,N3作为N1,N4作为N2,null作为Color,null作为State,S_Name作为S_Name来自tableB

答案 1 :(得分:1)

你可以做的就是使用union all

来调用它
select name, n1, n2, color, state, null as 's_name' as recordtype from tablea
union all
select null as 'name', n3 as 'n1', n4 as 'n2', null as 'color', null as 
'state', s_name from tableb 

答案 2 :(得分:1)

create table tablc as
select name,n1,n2,color,State,' ' as sname FROM tablea
union 
select '' as name,n3,n4,'' as color ,'' as State ,'s.name' as sname from tableb 

答案 3 :(得分:1)

上面提到了两个表    当我们运行代码时

Create table tablc as
select name,n1,n2,color,State,' ' as sname FROM tablea
union 
select '' as name,n3,n4,'' as color ,'' as State ,'s.name' as sname from tableb 

新表格将创建enter image description here

输出将显示为表tablc