两种方式在MySql中加入

时间:2012-07-20 13:38:25

标签: mysql join

我正在尝试使用4个不同的表构建查询:

  • Users_Licences
  • 许可证
  • 产品
  • 请求

Users有多个Licences,存储在Users_Licences中。 Products有多个Requests,而Request表格中您有Products表中的目标许可证source_licence

我想列出指定用户在Products表中拥有目标许可证和源许可证(通过Users_Licences)的所有请求。

复杂但这是我现在的地方(不工作):

SELECT 
    Request.id AS offer_id, Request.product_id, 
    Request.licence_id AS target_licence_id, 
    Request.trans_price, Products.source_licence_id    
FROM 
    Request    
JOIN 
    Products ON Request.product_id = Products.id    
JOIN 
    Licences ON Products.source_licence_id = Licences.id    
JOIN 
    Licences ON Request.licence_id = Licences.id    
JOIN 
    Users_Licences ON Licences.id = Users_Licences.licence_id    
WHERE 
    Users_Licences.user_id = '$user_id'    
GROUP BY 
    Request.id    
ORDER BY 
    Request.trans_price DESC
你可以帮帮我吗?如果我删除该行

JOIN Licences ON Products.source_licence_id = Licences.id

它有效,但我有部分结果......谢谢!

1 个答案:

答案 0 :(得分:1)

当您使用表格时,您需要使用不同的别名

SELECT Request.id AS offer_id, Request.product_id, Request.licence_id AS target_licence_id, Request.trans_price 
, Products.source_licence_id     
FROM Request     
JOIN Products ON Request.product_id = Products.id     
JOIN Licences as l1 ON Products.source_licence_id = l1.id     
JOIN Licences as l2 ON Request.licence_id = l2.id     
JOIN Users_Licences ON l2.id = Users_Licences.licence_id     
WHERE Users_Licences.user_id='$user_id'     
GROUP BY Request.id     
ORDER BY Request.trans_price DESC