数据库(四)——SQL语句 使用子查询,联结表

81 阅读1分钟
  1. 利用子查询进行过滤
select order_num from OrderItems where prod_id = 'RGAN01'; //搜索结果是20007,2008
select cust_id from Orders where order_num in (20007,2008);
//综合以上得出以下句子
select cust_id from Orders where order_num in (select order_num from OrderItems where prod_id = 'RGAN01');
  1. 在where子句中使用子查询能够编写出功能很强且灵活的SQL语句。作为子查询的select 语句只能查询单个列。

  2. 作为计算字段使用子查询

select cust_name,cust_state,(select count(*) from orders where Orders.cust_id = Customers.cust_id) as orders from Customers order by cust_name;

联结表

联结是一种机制,用来在一条select语句中关联表

select vend_name,prod_name,prod_price from Vendors ,Products where Vendors.vend_id = Products.vend_id;

在引用的列可能出现歧义时,必须使用完全限定列名(用一个句点分隔表名和列名)。
笛卡儿积:由没有联结条件的表关系返回的结果为笛卡儿积。检索出的行的数目将是第一个表中的行数乘以第二个表中的行数。

select vend_name ,prod_name,prod_price from Vendors,Products;
  1. 内联结
  2. 联结多个表
select prod_name,vend_name,prod_price,quantity from OrderItems,Products,Vendors WHERE Products.vend_id = Vendors.vend_id AND OrderItems.prod_id = Products.prod_id AND order_num = 20007;

3.性能考虑:不要联结不必要的表,联结的表越多,性能下降越厉害。