第14课组合查询

第1课了解SQL                第12课联结表

第2课检索数据                第13课创建高级联结

第3课排序检索数据         第14课组合查询

第4课过滤数据                第15课插入数据

第5课高级数据过滤         第16课更新删除数据

第6课用通配符进行过滤  第17课创建和操纵表

第7课创建计算字段         第18课使用视图

第8课使用函数处理数据

第9课汇总数据

第10课分组数据

第11课使用子查询


组合查询:执行多个查询(多条select语句),并将结果作为一个查询结果集返回。也称为并、复合查询。

UNION操作符

        1,select cust_name, cust_contact, cust_email from customers where cust_state in ('il', 'in', 'mi');

        

        2,select cust_name, cust_contact, cust_email from customers where cust_name='Fun4All';

        

        为了将1,2语句的查询结果组合起来。可以a,使用多条where子句,b,使用union操作符。

        a,使用多条where子句:select cust_name, cust_contact, cust_email from customers where cust_state in ('il', 'in', 'mi') or cust_name='Fun4All'; 

        b,使用union操作符:select cust_name, cust_contact, cust_email from customers where cust_state in ('il', 'in', 'mi') union select cust_name, cust_contact, cust_email from customers where cust_name='Fun4All';

        

        从性能上看使用多条 WHERE 子句条件 还是 UNION 应该没有实际的差别。

UNION规则:1,UNION 必须由两条或两条以上的 SELECT 语句组成,语句之间用关键字UNION分隔。2,UNION 中的每个查询必须包含相同的列、表达式或聚集函数(不过,各个列不需要以相同的次序列出)。3,列数据类型必须兼容:类型不必完全相同,但必须是 DBMS 可以隐含转换的类型(例如,不同的数值类型或不同的日期类型)。

包含或取消重复的行:UNION 从查询结果集中自动去除了重复的行,结果与一条SELECT 语句中使用多个WHERE子句一样。UNION默认去除重复行,如果想返回所有的匹配行,可使用UNION ALL。

        union all包含重复行select cust_name, cust_contact, cust_email from customers where cust_state in ('il', 'in', 'mi') union all select cust_name, cust_contact, cust_email from customers where cust_name='Fun4All';

        

对组合查询结果排序:在用UNION组合查询时,只能使用一条ORDER BY子句,它必须位于最后一条 SELECT 语句之后,DBMS 将用它来排序所有 SELECT 语句返回的所有结果。不允许使用多条 ORDER BY 子句。

        select cust_name, cust_contact, cust_email from customers where cust_state in ('il', 'in', 'mi') union select cust_name, cust_contact, cust_email from customers where cust_name='Fun4All' order by cust_name,cust_contact;

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挚艾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值