我无法理解这一点。
我有一个名为1_related的表
id,prod_pack,fk_prod_pack_id,fk_prod_pack_related,fk_prod_pack_related_id
'2', '0', '102', '0', '2482'
'3', '0', '102', '0', '3147'
'2294', '0', '102', '1', '10'
我还有另外两个名为1_products和1_packages的表
我想根据fk_prod_pack_related的值加入任一表的内容(0表示1_products表,1表示1_packages表)
此查询从1_related返回第2行和第3行,并加入1_products
的内容SELECT
r . *, p . *
FROM
1_related AS r
INNER JOIN
1_products as p ON r.fk_prod_pack_related_id = p.id
and r.fk_prod_pack_related = 0
WHERE
r.prod_pack = 0
and r.fk_prod_pack_id = 102
但是我也需要来自1_packages的数据,所以我尝试了这个,但它没有返回任何内容
SELECT
r . *, p . *, s . *
FROM
1_related AS r
INNER JOIN
1_products as p ON r.fk_prod_pack_related_id = p.id
and r.fk_prod_pack_related = 0
INNER JOIN
1_packages as s ON r.fk_prod_pack_related_id = s.id
and r.fk_prod_pack_related = 1
WHERE
r.prod_pack = 0
and r.fk_prod_pack_id = 102
答案 0 :(得分:1)
您需要左外连接,因为只有一个查询匹配:
SELECT
r . *, p . *, s . *
FROM
1_related AS r
left outer JOIN
1_products as p ON r.fk_prod_pack_related_id = p.id
and r.fk_prod_pack_related = 0
left outer JOIN
1_packages as s ON r.fk_prod_pack_related_id = s.id
and r.fk_prod_pack_related = 1
WHERE
r.prod_pack = 0
and r.fk_prod_pack_id = 102