mysql合并表

Posted Hu知非

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql合并表相关的知识,希望对你有一定的参考价值。

有如下两张表

a
+------+------+---------+
| uid  | name | addtime |
+------+------+---------+
|    1 | tom  |    2001 |
|    2 | jack |    2002 |
|    3 | alex |    2003 |
+------+------+---------+

b
+------+-------+---------+
| uid  | title | addtime |
+------+-------+---------+
|    1 | rain  |    2004 |
|    2 | snow  |    2005 |
|    3 | wind  |    2006 |
+------+-------+---------+

 

join是将两个表横向合并,就是通过on的条件将一个表追加在另一个表后边,新表相对于原来的两个表字段增多了。

 

mysql> select * from b left join a on b.uid = a.uid;
+------+-------+---------+------+------+---------+
| uid | title | addtime | uid | name | addtime |
+------+-------+---------+------+------+---------+
| 1 | rain | 2004 | 1 | tom | 2001 |
| 2 | snow | 2005 | 2 | jack | 2002 |
| 3 | wind | 2006 | 3 | alex | 2003 |
+------+-------+---------+------+------+---------+ 

union是将两个表竖向合并,新表字段不会多于原表。

mysql> select * from b union select * from a;
+------+-------+---------+
| uid  | title | addtime |
+------+-------+---------+
|    1 | rain  |    2004 |
|    2 | snow  |    2005 |
|    3 | wind  |    2006 |
|    1 | tom   |    2001 |
|    2 | jack  |    2002 |
|    3 | alex  |    2003 |
+------+-------+---------+

mysql> select title,addtime from b union select name,addtime from a; 
+-------+---------+                                                  
| title | addtime |                                                  
+-------+---------+                                                  
| rain  |    2004 |                                                  
| snow  |    2005 |                                                  
| wind  |    2006 |                                                  
| tom   |    2001 |                                                  
| jack  |    2002 |                                                  
| alex  |    2003 |                                                  
+-------+---------+                                                  

参考:http://bbs.csdn.net/topics/390410010

 

以上是关于mysql合并表的主要内容,如果未能解决你的问题,请参考以下文章

4.3 合并重复的条件执行片段

mysql查询数据怎么合并为一条

mysql多表查询合并到一个临时表,怎么再加一列并把各自的表名加上?

Mysql合并表原理

MySQL 查询;合并两个表

如何合并两个 MySQL 表?