首页 > 解决方案 > 如何在sql中将4个表连接在一起

问题描述

我有客户、产品、订单orderdetails 4 表。他们的关系是这样的。反应

我的 SQL 代码如下所示:

select customers.CUSTOMERNAME, customers.STATE, customers.creditlimit
from customers
INNER JOIN ORDERS ON customers.customernumber = ORDERS.CUSTOMERNUMBER;

select ORDERDETAILS.PRICEEACH, ORDERDETAILS.QUANTITYORDERED
from ORDERDETAILS
inner join orders on ORDERS.ORDERNUMBER = ORDERDETAILS.ordernumber;

select products.productname
from products
inner join orderdetails on orderdetails.productcode = products.productcode;

我想将 4 个表加入到一个带有选定段的表中。我怎样才能做到这一点?

标签: sql

解决方案


您可以执行以下操作

SELECT c.CUSTOMERNAME
    , o.CUSTOMERNUMBER
    , od.PRICEEACH
    , p.productname
FROM customers c
INNER JOIN orders o
    on c.customernumber = o.customernumber
INNER JOIN ORDERDETAILS od
    on o.ORDERNUMBER = od.ORDERNUMBER
INNER JOIN products p
    on od.productcode = p.productcode

推荐阅读