高级数据操作--联合查询

一.联合查询

 1 -- 关键字: union 
 2 
 3 -- 语法
 4 select 语句1 
 5 union[union 选项]
 6 select 语句2
 7 union[union 选项]
 8 ......
 9 union[union 选项]
10 select 语句n;

所谓的联合查询,就是将多个查询语句的结果进行纵向上的拼接,也就是将select语句2的查询结果放在select语句1的后面!很显然,总的记录数增加了,但是字段的数量并没有增加!

既然是多个查询记录的拼接,所以联合查询有一个最基本的语法,就是各个select语句查询结果的字段数应该是一样的,比如,不能一个3列,一个是4列!

 

这里的union选项跟以前学习的select选项是一样的,只是它们的默认值不一样:

1 -- 这里的union跟select的选项一样的,只是默认值不一样
2 -- all:显示全部记录
3 -- distinct : 去除重复数据(union默认选择的值)
4 select * from php_student
5 union all
6 select * from php_student;

当然,上面的查询结果毫无意义!

1.union的应用

表和数据

create table php_student(
    id int primary key auto_increment,
    name varchar(20),
    gender enum('male','female'),
    class_id tinyint unsigned,
    age int unsigned,
    home varchar(40),
    score tinyint unsigned
);

insert into php_student values
    (null,'孙悟空','male',17,600,'花果山',98),
    (null,'蜘蛛精','female',18,500,'花果山',90),
    (null,'猪悟能','male',17,700,'高老庄',88),
    (null,'沙悟净','male',17,750,'流沙河',78),
    (null,'唐僧','male',17,30,'东土大唐',100),
    (null,'高翠兰','female',16,18,'高老庄',70),
    (null,'皇后','female',16,18,'东土大唐',73),
    (null,'小龙女','female',17,30,'流沙河',80),
    (null,'小猴子','male',16,100,'花果山',95),
    (null,'皇帝','male',16,60,'东土大唐',93),
    (null,'高翠华','female',16,16,'高老庄',80);
union主要应用在以下的几种情形:
第一.获得数据的条件,在同一个select语句中存在某种逻辑上的冲突,
或者说很难在同一个逻辑内表示,此时,需要拆分成多个逻辑,也就是在多个
select语句中分别实现再将最终的结果组合到一起!

 

/*
比如:现在要查询上面php_student中,高老庄的一个score最高分,和花果山中的一个最低分!
*/
-- 先查高老庄中的最高分
select * from php_student where home='高老庄' order by score desc limit 1;
-- 在查花果山中最低分
select * from php_student where home='花果山' order by score asc limit 1;

-- 把两个查询结果连接在一起
select * from php_student where home='高老庄' order by score desc limit 1
union
select * from php_student where home='花果山' order by score asc limit 1;  -- 运行出错

这里有几点需要注意的地方:

1,  联合查询中如果使用到了order by,那么就必须要对select子句加上一对小括号();

    

1 (select * from php_student where home='高老庄' order by score desc limit 1)
2  union
3 (select * from php_student where home='花果山' order by score asc limit 1); -- 运行ok

一个小测试:

1 -- (一个问题)把高老庄按score进行降序排序,并对花果山按score升序排序,并联合在一起
2 (select * from php_student where home='高老庄' order by score desc )
3  union
4 (select * from php_student where home='花果山' order by score asc ); -- 结果是混乱,不符合要求

2,  如果联合查询中出现了order by子句,就必须配合上limit子句才能生效,当然,如果确实想显示全部的数据,可以在limit的后面加上一个很大的数,比如999999;

1 (select * from php_student where home='高老庄' order by score desc limit 9999999)
2 union
3 (select * from php_student where home='花果山' order by score asc  limit 9999999); -- 执行ok

第二,   如果一张数据表的记录数特别大,往往会导致查询效率的低下,此时,我们可以采取某种方式或者规律对数据表进行“水平切割”,此时,每张数据表的结构都是一样的,只是里面存放的数据不一样!此时,在根据某些条件进行查询的时候,可能每一张表都需要查询,最后通过union语句联合到一起!

 

原文地址:https://www.cnblogs.com/mrszhou/p/7470548.html