UNION用的比较多union all是直接连接,取到得是所有值,记录可能有重复 union 是取唯一值,记录没有重复
UNION 和 UNION ALL 的语法都是: [SQL 语句 1] UNION [SQL 语句 2] 效率: UNION和UNION ALL关键字都是将两个结果集合并为一个,但这两者从使用和效率上来说都有所不同。 1、对重复结果的处理:UNION在进行表链接后会筛选掉重复的记录,Union All不会去除重复记录。 2、对排序的处理:Union将会按照字段的顺序进行排序;UNION ALL只是简单的将两个结果合并后就返回。 从效率上说,UNION ALL 要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复数据且不需要排序时的话,那么就使用UNION ALL。
简单使用:
表一 test1
id | name |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王五 |
表二 test2
id | name |
---|---|
4 | 小一 |
5 | 小二 |
6 | 小三 |
查询语句是这样的:
select id ,name from test1
union select id, name from test 2 where id = 4
limit 1
这个sql的目的是,从两张表中,取出id = 4 的数据,如果有多条,只取一条。
但是查询结果是:
id | name |
---|---|
1 | 张三 |
经过分析发现,这条sql等效于下面:
select id ,name from test1
union ( select id, name from test 2 where id = 4 )
limit 1
这条sql(下面这个),查询结果是:
select id ,name from test1union (
select id, name from test 2 where id = 4 )
id | name |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王五 |
4 | 小一 |
然后limit 1, 取出来的就是第一条,即张三-1
所以这条sql应该修改成下面:
第一种修改方式:
select id ,name from test1 where id = 4
union select id, name from test 2 where id = 4
limit 1
第二种修改方式:
select t.* from (
select id ,name from test1
union select id, name from test 2 ) t where t.id = 4
limit 1