我正在尝试使用4个不同的表构建查询:
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
它有效,但我有部分结果......谢谢!
答案 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