创建联结
分别从商户表和产品表中查询出商户名字、产品名字、产品价格
注意:在引用的列可能出现二义性时,必须是要完全限定列名(表名.列名)
SELECT vend_name, prod_name, prod_price FROM vendors, products WHERE vendors.vend_id = products.vend_id ORDER BY vend_name, prod_name;
内联结
内联结:基于两个表之间的相等测试,所使用的联结称为内联结
上述的联结方式也可以写作:
SELECT vend_name, prod_name, prod_price FROM vendors INNER JOIN products ON vendors.vend_id = products.vend_id;
左联结
左联结:LEFT JOIN 关键字从左表(table1)返回所有的行,即使右表(table2)中没有匹配。如果右表中没有匹配,则结果为 NULL
查询所有客户,包括那些没有订单的客户
SELECT customers.cust_id, orders.order_num FROM customers LEFT OUTER JOIN orders ON customers.cust_id = orders.cust_id;
右联结
右联结:RIGHT JOIN 关键字从右表(table2)返回所有的行,即使左表(table1)中没有匹配。如果左表中没有匹配,则结果为 NULL
从右边的表中选择所有行
SELECT customers.cust_id, orders.order_num FROM customers RIGHT OUTER JOIN orders ON orders.cust_id = customers.cust_id;
使用带聚集函数的联结
查询所有客户以及每个客户所下的订单数
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;