SQL必知必会 第14课 组合查询

不念不忘少年蓝@ 2022-11-07 13:18 271阅读 0赞

14.1 组合查询

SQL允许执行多个查询(多条SELECT语句),并将结果作为一个查询结果集返回。这些组合查询通常称为或复合查询。

有两种情况需要使用组合查询:

  • 在一个查询中从不同的表返回结构数据;
  • 对一个表执行多个查询,按一个查询返回数据。

14.2 创建组合查询

可用UNION操作符来组合数条SQL查询。

UNION

在每条select语句之间放上关键字UNION即可。

  1. # UNION
  2. select cust_name, cust_contact, cust_email
  3. from customers
  4. where cust_state in ('IL', 'IN', 'MI')
  5. union
  6. select cust_name, cust_contact, cust_email
  7. from customers
  8. where cust_name = 'Fun4All';

在这里插入图片描述

UNION 规则

  • UNION必须由两条或两条以上的SELECT语句组成,语句之间用关键字UNION分隔
  • UNION 中的每个查询必须包括相同的列、表达式或聚集函数
  • 列数据类型必须兼容:类型不必完全相同,但必须是DBMS可以隐含转换的类型

包含或取消重复的行

UNION从查询结果集中自动去除了重复的行。但如果不想去除(返回所有匹配行),可使用UNION ALL 而不是 UNION

  1. select cust_name, cust_contact, cust_email
  2. from customers
  3. where cust_state in ('IL', 'IN', 'MI')
  4. union all
  5. select cust_name, cust_contact, cust_email
  6. from customers
  7. where cust_name = 'Fun4All';

在这里插入图片描述

对组合查询结果排序

在用UNION组合查询时,只能使用一条ORDER BY子句,必须位于最后一条SELECT语句之后。

  1. select cust_name, cust_contact, cust_email
  2. from customers
  3. where cust_state in ('IL', 'IN', 'MI')
  4. union
  5. select cust_name, cust_contact, cust_email
  6. from customers
  7. where cust_name = 'Fun4All'
  8. order by cust_name, cust_contact;

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读