1、使用表别名
缩短SQL语句;
允许在单条SELECT语句中多次使用相同的表
表别名只在查询执行使用中使用。与列别名不一样,表别名不返回到客户机。
select cust_name,cust_contact
from customers as c,orders as o,orderitems as oi
where c.cust_id = o.cust_id
and oi.order_num= o.order_num
and prod_id='TNT2';
2、自联结
单条SELECT语句中不止一次引用相同的表。
- 子查询
select prod_id,prod_name
from products
where vend_id=(select vend_id from products where prod_id='DTNTR');
- 自联结
select prod_id,prod_name
from products as p1,products as p2
where p1.vend_id=products.vend_id
and products.prod_id='DTNTR';
自联结通常作为外部语句用来替代从相同表中检索数据时使用的子查询语句。虽然与子查询结果是相同的,但有时候比子查询快的多。
3、自然联结
只能选择那些唯一的列,通过对表使用通配符(SELECT *),对所有其他表的列使用明确地子集来完成。自然联结排除多次出现,每个列只返回一次。
select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id
and oi.order_num=o.order_num
and prod_id='FB';
该实例中,通配符只对第一个表使用。所有其他列明确列出,所以没有重复的列被检索出来。
4、外部联结
联结都是一个表中的行与另一个表中的行相关联。但有时候需要包含那些没有关联行的那些行。
- LEFT OUTER JOIN ON
- RIGHT OUTER JOIN ON
select customers.cust_id,orders.order_num
from customers left outer join orders
on customers.cust_id=orders.cust_id;
LEFT表示包含其所有行的表(LEFT指出的是OUTER JOIN左边的表)。
5、使用聚集函数的联结
select customers.cust_name,
customers.cust_id,
count(orders.order_num) as num_ord
from customers inner join orders
on customers.cust_id=orders.cust_id
group by customers.cust_id;