mysql中的union⽤法
UNION在mysql中被称为集合操作,操作类型分为两种:UNION DISTINCT 和 UNION ALL;注意:UNION和UNION DISTINCT是⼀样的功能。UNION功能为合并多个查询的结果并去重,UNION ALL的功能为合并多个查询的结果不去重。
集合操作时,两边的输⼊必须拥有相同的列数,如果数据类型不同的话,mysql会⾃动进⾏隐式转化 ;同时,结果列的名称由第⼀个查询的列的名称决定。下⾯看⼀下例⼦:
sql语句为:SELECT 'abc' as o,'haha' as p,4 as q FROM DUAL UNION SELECT 'abc' as a,'haha',4 FROM DUAL;结果是:
狗字
如果是:SELECT 'abc' as o,'haha' as p,4 as q FROM DUAL UNION ALL SELECT 'abc' as a,'haha',4 FROM DUAL;
如果两次查询的列个数不⼀致,如:SELECT 'abc' as o,'haha' as p,4 as q FROM DUAL UNION ALL SELECT 'abc' as a,'haha' FROM DUAL;
光景的近义词在多个列查询时,只要有⼀个列的数据不⼀致时,都是⽆法去重的;也就是去重是每个列的数据完全⼀致,⽐如:SELECT 'abc' as o,'haha' as p,4 as q FROM DUAL UNION DISTINCT SELECT 'abc' as a,'haha',5 FROM DUAL;
这⼏个例⼦可以看出UNION (DISTINCT) 与 UNION ALL的⽤法了吧,下⾯讲⼀下UNION (DISTINCT)的实现⽅式:
⼀:创建⼀张虚拟表;100位新中国成立以来感动中国人物>乌龟种类鉴别图片
⼆:对这张虚拟表的列添加唯⼀索引,即UNIQUE INDEX;
三:将结果插⼊虚拟表
米罗作品
四:返回虚拟表;
如何判断是否创建⼀个虚拟表,我们可以通过⼀下语句判断:
SHOW STATUS LIKE 'Created_tmp_tables';
鸡肉简笔画SELECT 'abc' as o,'haha' as p,4 as q FROM DUAL UNION SELECT 'abc' as a,'haha',4 FROM DUAL;
SHOW STATUS LIKE 'Created_tmp_tables'; 结果是:
鲍鱼属于
书五行属性是什么可见结果3⽐结果1多1,在操作第⼆个 UNION语句时创建了⼀个虚拟表;如果UNION创建了索引,插
⼊会相对变慢