SQL必知必会 第11课 使用子查询

以你之姓@ 2022-11-07 11:57 54阅读 0赞

11.1 子查询

任何SQL语句都是查询,但此术语一般指SELECT语句。
SQL还允许创建子查询,即嵌套在其他查询中的查询。

11.2 利用子查询进行过滤

  1. # 列出订购物品RGAN01的所有顾客
  2. select cust_name, cust_contact
  3. from customers
  4. where cust_id IN (
  5. select cust_id
  6. from orders
  7. where order_num IN(
  8. select order_num
  9. from orderitems
  10. where prod_id = 'RGAN01'));

在这里插入图片描述
对于能嵌套的子查询的数目没有限制,不过由于性能的限制,不能嵌套太多的子查询。

11.3 作为计算字段使用子查询

  1. # 列出customers表中每个顾客的订单总数
  2. select cust_name, cust_state, (select count(*) from orders where orders.cust_id = customers.cust_id) as orders
  3. from customers
  4. order by cust_name;

在这里插入图片描述
其中orders是一个计算字段,它是由圆括号中的子查询建立的。

子查询中的where子句与前面使用的where子句稍有不同,因为它使用了完全限定列名,而不只是列名(cust_id)。

发表评论

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

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

相关阅读