我写了以下查询,但不起作用。我想知道如何让它发挥作用。这是一个双JOIN查询,无法正常工作。
SELECT oc_download.download_id, oc_product_to_download.download_id, oc_download_description.download_id
FROM oc_download
LEFT JOIN oc_product_to_download
ON oc_download.download_id = oc_product_to_download.download_id
LEFT JOIN
oc_download.download_id = oc_download_description.download_id
WHERE oc_product_to_download.product_id = 89
使用单个JOIN可以正常工作,但添加第二个JOIN则失败。这是干净的工作一个JOIN查询:
SELECT oc_download.download_id, oc_product_to_download.download_id, oc_download_description.download_id
FROM oc_download
LEFT JOIN oc_product_to_download
ON oc_download.download_id = oc_product_to_download.download_id
WHERE oc_product_to_download.product_id = 89
如何在一个查询中使用多个JOIN?
答案 0 :(得分:2)
您忘记了第二次加入中的表名
SELECT d.download_id, p.download_id, dd.download_id
FROM oc_download d
LEFT JOIN oc_product_to_download p ON d.download_id = p.download_id
LEFT JOIN oc_download_description dd ON d.download_id = dd.download_id
WHERE p.product_id = 89
您的where
子句会将您的left join
变为inner join
。如果您不想这样,那么请将您的查询更改为
SELECT d.download_id, p.download_id, dd.download_id
FROM oc_download d
LEFT JOIN oc_product_to_download p ON d.download_id = p.download_id
AND p.product_id = 89
LEFT JOIN oc_download_description dd ON d.download_id = dd.download_id
答案 1 :(得分:2)
这是您使用表别名和正确的join
语法修正了一下您的查询:
SELECT od.download_id, opd.download_id, odd.download_id
FROM oc_download od LEFT JOIN
oc_product_to_download opd
ON od.download_id = opd.download_id LEFT JOIN
oc_download_description odd
od.download_id = odd.download_id
WHERE opd.product_id = 89;
您正在使用left join
,但这似乎是不必要的。 on
子句撤消第一个外连接,将其转换为内连接(不匹配的行将具有NULL
值,这些值将由where
子句过滤掉。事实上,我猜你的数据在被连接的列之间有明确定义的外键关系。如果是这种情况,您应该使用inner join
(或仅join
)进行查询:
SELECT od.download_id, opd.download_id, odd.download_id
FROM oc_download od JOIN
oc_product_to_download opd
ON od.download_id = opd.download_id JOIN
oc_download_description odd
od.download_id = odd.download_id
WHERE opd.product_id = 89;
left join
具有误导性,因为它暗示某些键可能不匹配。您还冒着混淆优化器的风险。