MySQL UNION 语法
MySQL UNION 用于把来自多个 SELECT 语句的结果组合到一个结果集合中。语法为:
SELECT column,... FROM table1
UNION [ALL]
SELECT column,... FROM table2
...
在多个 SELECT 语句中,对应的列应该具有相同的字段属性,且第一个 SELECT 语句中被使用的字段名称也被用于结果的字段名称。
UNION 与 UNION ALL 的区别
当使用 UNION 时,MySQL 会把结果集中重复的记录删掉,而使用 UNION ALL ,MySQL 会把所有的记录返回,且效率高于 UNION。
MySQL UNION 用法实例
UNION 常用于数据类似的两张或多张表查询,如不同的数据分类表,或者是数据历史表等。下面是用于例子的两张原始数据表:
article 文章表:
aid | title | content |
1 | 文章1 | 文章1正文内容... |
2 | 文章2 | 文章2正文内容... |
3 | 文章3 | 文章3正文内容... |
blog 日志表:
bid | title | content |
1 | 日志1 | 日志1正文内容... |
2 | 文章2 | 文章2正文内容... |
3 | 日志3 | 日志3正文内容... |
上面两个表数据中,aid=2 的数据记录与 bid=2 的数据记录是一样的。
使用 UNION 查询
查询两张表中的文章 id 号及标题,并去掉重复记录:
SELECT aid,title FROM article UNION SELECT bid,title FROM blog
返回查询结果如下:
aid | title |
1 | 文章1 |
2 | 文章2 |
3 | 文章3 |
1 | 日志1 |
3 | 日志3 |
UNION 查询结果说明
- 重复记录是指查询中各个字段完全重复的记录,如上例,若 title 一样但 id 号不一样算作不同记录。
- 第一个 SELECT 语句中被使用的字段名称也被用于结果的字段名称,如上例的 aid。
- 各 SELECT 语句字段名称可以不同,但字段属性必须一致。
使用 UNION ALL 查询
查询两张表中的文章 id 号及标题,并返回所有记录:
SELECT aid,title FROM article UNION ALL SELECT bid,title FROM blog
返回查询结果如下:
aid | title |
1 | 文章1 |
2 | 文章2 |
3 | 文章3 |
1 | 日志1 |
2 | 文章2 |
3 | 日志3 |
显然,使用 UNION ALL 的时候,只是单纯的把各个查询组合到一起而不会去判断数据是否重复。因此,当确定查询结果中不会有重复数据或者不需要去掉重复数据的时候,应当使用 UNION ALL 以提高查询效率。
DB::query("SELECT * FROM (SELECT itemid, addtime, title, type, introduce, forwardingid, forwarding_type, comments, likes, hits, '' as totime, '' as vote_min, '' as vote_max, '' as votes, username, status, edittime FROM `tableA` UNION SELECT itemid, addtime, title, type, introduce, forwardingid, forwarding_type, comments, likes, hits, totime, vote_min, vote_max, votes, editor as username, status, edittime FROM `tableB` UNION SELECT itemid, addtime, title, type, introduce, forwardingid, forwarding_type, comments, likes, hits, '' as totime, '' as vote_min, '' as vote_max, '' as votes, editor as username, status, edittime FROM `tableC`) d WHERE d.username " . $where . " AND d.status=3 AND (d.totime>" . time() . " OR d.totime='') ORDER BY d.addtime DESC LIMIT {$start}, 10");
联合查询:
如果你想把多个查询的结果合并在一起创建一个结果集,我们可以使用UNION查询来做。
(1)列名
注意:查询的列名不一定要相同,结果集中的列名,是以第一个表的查询结果为准。
(2)关于重复记录
如果有重复的记录,则只显示一条。
我就希望把所有的显示出来,这个时候可以使用 UNION ALL
(3)关于排序
select i,c from t1 union select i,d from t3 order by i desc;
错误:
mysql> select i,c from t1 order by i desc union
select i,d from t3 order by i desc;
ERROR 1221 (HY000): Incorrect usage of UNION and ORDER BY
加括号:
(select i,c from t1 order by i desc) union (select i,d from t3 order by i desc);
结果并未排序
需要再加limit
(select i,c from t1 order by i desc limit 3) union (select i,d from
t3 order by i desc limit 3)
这才ok了!
注意,
a. 在UNION 中,你要对结果集先排序,后union时候,需要将其用括号括起来
b. 要使用Limit,排序结果才可以起作用。