日期:2014-05-17  浏览次数:20588 次

跟燕十八学习PHP-第二十八天-union用法深入讲解




/** 
燕十八 公益PHP培训 
课堂地址:YY频道88354001 
学习社区:www.zixue.it 
**/






mysql> create table a (
    -> id char(1),
    -> num int
    -> )engine myisam charset utf8;
Query OK, 0 rows affected (0.17 sec)


mysql> 
mysql> insert into a values ('a',5),('b',10),('c',15),('d',10);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0


mysql> 
mysql> create table b (
    -> id char(1),
    -> num int
    -> )engine myisam charset utf8;
Query OK, 0 rows affected (0.17 sec)


mysql> 
mysql> insert into a values ('b',5),('c,15),('d',20),('e',99);
    '> \c
    '> '\c
mysql> insert into b values ('b',5),('c',15),('d',20),('e',99);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0


mysql> select * from a;
+------+------+
| id   | num  |
+------+------+
| a    |    5 |
| b    |   10 |
| c    |   15 |
| d    |   10 |
+------+------+
4 rows in set (0.00 sec)


mysql> select * from b;
+------+------+
| id   | num  |
+------+------+
| b    |    5 |
| c    |   15 |
| d    |   20 |
| e    |   99 |
+------+------+
4 rows in set (0.00 sec)


mysql> #可用用左连接来做
mysql> select a.*,b.* from 
    -> a left join b on a.id=b.id;
+------+------+------+------+
| id   | num  | id   | num  |
+------+------+------+------+
| a    |    5 | NULL | NULL |
| b    |   10 | b    |    5 |
| c    |   15 | c    |   15 |
| d    |   10 | d    |   20 |
+------+------+------+------+
4 rows in set (0.00 sec)


mysql> #再把上面的结果看成一张临时表,再次from型子查询,计算a.num+b.num的和
mysql> #这个思路,课下同学们自己来试.如遇到坑,查 ifnull函数
mysql> #而且少了e, 只好左连 union 右连,再子查询
mysql> 
mysql> #换个思路,先把2张表的数据union到一块,再利用sum()函数来相加
mysql> select * from a;
+------+------+
| id   | num  |
+------+------+
| a    |    5 |
| b    |   10 |
| c    |   15 |
| d    |   10 |
+------+------+
4 rows in set (0.00 sec)


mysql> select * from b;
+------+------+
| id   | num  |
+------+------+
| b    |    5 |
| c    |   15 |
| d    |   20 |
| e    |   99 |
+------+------+
4 rows in set (0.00 sec)


mysql> select * from a
    -> union
    -> select * from b;
+------+------+
| id   | num  |
+------+------+
| a    |    5 |
| b    |   10 |
| c    |   15 |
| d    |   10 |
| b    |    5 |
| d    |   20 |
| e    |   99 |
+------+------+
7 rows in set (0.00 sec)


mysql> #再sum一下,
mysql> select id,sum(num) from (
    -> 
    ->  select * from a