《MySQL必知必会》第十五十六章-联结表与创建高级联结

创建联结(等值联结、内联结):
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 INNER JOIN Products
ON Vendors.vend_id = Products.vend_id;

联结多个表:
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;
 
  
使用表别名:
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 = 'RGAN01';
自联结:
SELECT c1.cust_id, c1.cust_name, c1.cust_contact
FROM Customers AS c1, Customers AS c2
WHERE c1.cust_name = c2.cust_name
AND c2.cust_contact = 'Jim Jones';  -- WHERE首先联结两个表,然后按第二个表中的cust_contact过滤数据,返回所需数据
自然联结:
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 = 'RGAN01';
外联结:
SELECT Customers.cust_id, Orders.order_num, Orders.cust_id
FROM Customers LEFT OUTER JOIN Orders
ON Customers.cust_id = Orders.cust_id;
使用带聚集函数的联结:
SELECT 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;
SELECT Customers.cust_id,
       COUNT(Orders.order_num) AS num_ord
FROM Customers LEFT OUTER JOIN Orders
ON Customers.cust_id = Orders.cust_id
GROUP BY Customers.cust_id;

你可能感兴趣的:(《MySQL必知必会》学习笔记,《MySQL必知必会》读书笔记)