创建联结

1、where联结

select vend_name, prod_name, prod_price
from vendors, products
where vendors.vend_id = products.vend_id
order by vend_name, prod_name;

结果:

\1.PNG

注意:这里如果省略where条件,会返回笛卡尔积结果

2、内部联结 inner join

select vend_name, prod_name, prod_price
from vendors inner join products
on vendors.vend_id = products.vend_id;

说明:这个例子返回的结果跟上一个例子完全一致。
上面两种写法,ANSI SQL规范首选inner join语法。
此外,尽管使用where字句定义联结的确比较简单,但是使用明确的联结语法能够确保不会忘记联结条件,有时候这样做也能影响性能。

3、联结多个表

SQL对一条select语句中可以联结的表的数目没有限制。创建联结的基本规则也相同。首先列出所有表,然后定义表之间的关系。

例如:

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 = 20005;

\2.PNG

说明:此例子显示编号为20005的订单中的物品。

之前曾有过一个例子,可以用联结表的方式改写:

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='TNT2'));
                           
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 = 'TNT2';
                           

使用不同类型的联结

上面我们使用的只是称为内部联结或等值联结的简单联结。下面介绍3中其他联结。

1、自联结

假如你发现某物品(其ID为DTNTR)存在问题,因此想知道生产该物品的供应商生产的其他物品是否有问题。

//使用子查询的方式实现
select prod_id, prod_name
from products
where vend_id = (select vend_id
            from products
            where prod_id = 'DTNTR');

//使用自联结的方式
select p1.prod_id, p1.prod_name
from products as p1, products as p2
where p1.vend_id = p2.vend_id
and p2.prod_id = 'DTNTR';

自联结通常作为外部语句用来替代从相同表中检索数据时使用的子查询语句。虽然最后的结果是相同的,但有时处理联结远比处理子查询快得多。

2、自然联结

自然联结排除多次出现。使每列只返回一次。
自然联结是这样一种联结,其中你只能选择那些唯一的列。

举例:

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';

3、外部联结

许多联结将一个表中的行与另一个表中行相联结。但有时候会需要包含没有关联行的那些行。

举例:

select customers.cust_id, orders.order_num
from customers left outer join orders
on customers.cust_id = orders.cust_id;

结果:

\3.PNG

使用带聚集函数的联结

举例:

select customers.cust_name
     customers.cust_id
     count(orders.order_num) as num_ord
from customers left join orders
on customers.cust_id = orders.cust_id
group by customers.cust_id;

结果:

\4.PNG


参考书籍:

  • MySQL必知必会


MySql

登陆发表评论