使用子查询
查询
任何SQL语句都是查询,一般指select语句
子查询
嵌套在其他查询中的查询
检索出订购物品RGAN01的所有顾客及信息(各订单的物品存储在相关的orderitems中,orders表只存顾客id,custumers表存放顾客的实际信息):
Select cust_name,cust_contact
From customers
Where cust_id in(select cust_id
From orders
Where order_num in (select order_num
From orderitems
Where prod_id=’RGAN01’));
注意:1.子查询的select语句只能查询单个列,企图查询多个列将返回错误结果
2.在实际使用中由于性能的限制,不能嵌套太多的子查询
作为计算字段使用子查询
假设需要显示在customers表中每个顾客的订单总数,订单与相应的顾客id存储在orders表中:
Select cost_name,
Cust_state,
(select count(*)
From orders
Where orders.cust_id=customers.cust_id) as orders
From customers
Order by cust_name;
其中orders是一个计算字段,由圆括号中的子查询建立,对查询出的每个顾客执行一次。
注意:1.子查询中的where子句与前面所使用的where有所不同,子查询中使用了完全限定列名(orders.cust_id),其目的是用于比较两个表中的cust_id,来避免歧义。
联结表
关系表
关系表设计的目的就是把信息分解成多个表,一类数据一个表。各表通过共同的值相互关联,形成关系数据库。好处:1.信息不重复,不会浪费时间和空间2.如果信息变动,只更新一个表中的单个记录,相关表中的数据不用变动3.数据不重复,则数据将是一致的,处理数据以及生成报表更简单。
联结
如上文所言,将数据分解到多个表中,更有效、方便处理,但是怎样用一条select语句检索出存放在多张表中的数据。此时便需要联结。使用特殊的语法,可以联结多个表返回一组输出。
创建联结:
Select vend_name,prod_name,prod_price
From vendors,products
Where vendors.vend_id=products.vend_id;
其中prod_name,prod_price在一个表中,而vend_name在另一个表中;where子句作为过滤条件,只包含那些匹配联结条件的行,若没有where子句,第一个表中的每一行将与第二个表中的每一行匹配。
注意:由于没有联结条件的表关系返回的结果为笛卡尔积,检索出的行的数目将是第一个表总的行数乘以第二个表中的行数。但是这样的结果往往是我们不需要的,因此不要忘记where子句的使用。
内联结
目前使用的联结称为等值联结,也叫内联结,基于两个表中的相等测试。其实可以对这种联结使用不同的语法,明确指定联结的类型:
Select vend_name,prod_name,prod_price
From vendors inner join products
on vendors.vend_id=products.vend_id;
联结多个表
SQL不限制select语句可以联结表的数目,创建联结的基本规则也相同。
Select vend_name,prod_name,prod_price,quantity
From vendors,products,orderitems
Where vendors.vend_id=products.vend_id
And orderitems.prod_id=products.prod_id
And order_num=20007;
注意:1.不要联结不必要的表,联结的表越多,性能下降得越厉害
2.SQL本身不限制每个联结约束中表的数目,但实际DBMS有所限制
在上文中使用子查询并不是执行复杂selelct操作的最有效方法,可使用联结的相同查询:
Select cust_name,cust_contact
From customers
Where cust_id in(select cust_id
From orders
Where order_num in (select order_num
From orderitems
Where prod_id=’RGAN01’));
VS
Select cust_name,cust_contact
From customers,orders,orderitems
Where customers.cust_id=orders.cust_id
And orderitems.order_num=orders.order_num
And prod_id=’RGAN01’;