SQL连接具有多个表的表

时间:2016-03-15 03:49:59

标签: sql join

我的SQL作业存在很多问题。特别是一旦我必须处理两个以上的表来获得所需的解决方案,我就会陷入困境。

一个例子是列出Almondton综合商店以太包含的每个订单的订单号和订单日期,其中包含消防车的订单行。

我尝试使用以下代码来完成此任务。

select order_num, order_date
from orders
where exists (select *
              from customer, order_line, item
              where orders.customer_num = customer.customer_num
                and customer_name = 'Almondton Genreal Store'
                 or orders.order_num = order_line.order_num
                and order_line.item_num = item.item_num
                and description = 'fire truck');

我一般需要知道如何处理一次使用两个以上的表。

1 个答案:

答案 0 :(得分:0)

您需要订单编号和日期来自客户名称为Almondton General Store的所有订单,并且所购买的商品为fire truck。您可以简单地将四个表连接在一起以获得结果:

SELECT o.order_num, o.order_date
FROM orders o
INNER JOIN customer c
    ON o.customer_num = c.customer_num
INNER JOIN order_line ol
    ON o.order_num = ol.order_num
INNER JOIN item i
    ON ol.item_num = i.item_num
WHERE c.customer_name = 'Almondton General Store' AND i.description = 'fire truck'