多表查询可以替代子查询,也不多说了直接敲例题!
例 1 : 列出每个客户的编号和名称,以及代表该客户的销售代表的编号、名字和姓氏。
SELECT customerNumber,customerName,salesRepEmployeeNumber,lastName,firstName from customers,employees where salesRepEmployeeNumber = employeeNumber;运行结果: 解析: 顾客和销售代表不在一张表里,所以我们用多表查询。这里where里的条件是用来将两张不同的表建立联系的。
例 2 : 查询顾客编号和姓名以及与之对应的支付日期和金额。
SELECT customers.customerNumber,customerName,paymentDate,amount from customers,payments where customers.customerNumber = payments.customerNumber;运行结果: 解析: 这里两张表中都有customerNumber,为了区分我们在他们之间加上表的名字。也可以简写,如下:
SELECT c.customerNumber,customerName,paymentDate,amount from customers c,payments p where c.customerNumber = p.customerNumber;例 3 : 列出在2005年5月1日之前下单的顾客编号,姓名和订单日期。
SELECT c.customerNumber,customerName,orderDate from customers c,orders o where c.customerNumber = o.customerNumber and orderdate > '2005-05-01';运行结果: 如果只要列出顾客信息可以用in子查询
SELECT customerNumber,customerName from customers where customerNumber in (select customerNumber from orders where orderDate > '2005-05-01')运行结果: 例 4 : 列出产品单号为“s18_1589”的订单编号
SELECT orderNumber from orders where exists (select * from orderdetails where orders.ordernumber = orderdetails.ordernumber and productCode = 'S18_1589')运行结果: 解析: 这里exist用于检查子查询中的任何记录的存在。如果子查询返回一条或多条记录,则exists运算符返回true。这里大家可能会想为什么不用如下代码:
SELECT orderNumber from orders where ordernumber = (select ordernumber from orderdetails where productCode = 'S18_1589')运行报错: 现在大家应该明白了
例 5 : 列出价格相同的产品编号,名称,价格。
SELECT a.productCode,a.productName,a.buyPrice from products a ,products b where a.buyPrice = b.buyPrice and a.productCode > b.productCode运行结果: 解析: 这里我们将一张表自连。最后一行代码是用来去除重复元素的。可能会有人有疑问,为什么不用<>(不等于)这里因为a <> b成立那么b <> a 也成立,这样会重复,如下: