相同和不同表中的不同ID的多个连接

时间:2015-02-04 06:38:54

标签: php mysql

我有不同的表格,而且我还要提取数据。

order table

orderId, clientId, buyerId, loadingCompanyId, productTypeId, orderStatusId

user table

userId, userCompanyName

orderStatus table

orderStatusId, orderStatusName,

productType table

productTypeId, productTypeName

所以这些表格。在order table clientId中,buyerId和loadingCompanyId来自用户的表userId,我想获取它的userCompanyName,orderStatusId来自orderStatus表,我想获取orderStatusName,最后一个是productTypeName,productTypeId来自productType表,想要获取productTypeName,但问题在于clientId,buyerId和loadingCompanyId这三个id是userId来自用户表,所以我如何获取客户端,买家和加载公司名称。

2 个答案:

答案 0 :(得分:1)

这是一些带别名的简单连接

select * 
from order 
join user client on clientId = client.userId
join user buyer on buyerId = buyer.userId
join user company on loadingCompanyId = company.userId
join orderStatus  on orderStatus.orderStatusId= order.orderStatusId
join productType on productType.productTypeId = order.productTypeId

答案 1 :(得分:0)

SELECT O.orderId, UserClient.userCompanyName As clientName, UserBuyer.userCompanyName AS buyerName, UserloadingCompany.userCompanyName AS buyerName, OS.orderStatusName, PT.productTypeName
FROM Order O
INNER JOIN user AS UserClient
ON O.clientId = UserClient.userId
INNER JOIN user AS UserBuyer
ON O.buyerId = UserBuyer.userId
INNER JOIN user AS UserloadingCompany
ON O.loadingCompanyId = UserloadingCompany.userId
INNER JOIN orderStatus AS OS
ON O.orderStatusId = OS.orderStatusId
INNER JOIN productType AS PT
ON O.productTypeId = PT.productTypeId