表C
|---------------------|------------------|------------------|------------------|
| ID | id_branch | id_supplier | qty |
|---------------------|------------------|------------------|------------------|
| 1 | 9 | | 2 |
|---------------------|------------------|------------------|------------------|
| 2 | | 20 | 3 |
|---------------------|------------------|------------------|------------------|
这是示例表,我希望从此表中获取结果。
我有一个查询
// P is product table
LEFT JOIN tableC AS C ON C.id_supplier = P.id_supplier AND C.id_branch = P.id_branch
我如何离开加入id_branch和id_supplier来显示数量?
目前它只显示来自id_branch的产品,甚至从id_supplier中选择产品。
如果我要将左连接更改为
// P is product table
LEFT JOIN tableC AS C ON C.id_supplier = P.id_supplier OR C.id_branch = P.id_branch
当选择显示所有产品时,它将显示来自id_supplier的所有产品,并且如果所选项目来自id_branch,它将显示来自id_branch的项目。
我如何才能正确地加入id_branch和id_supplier并显示有关它们的信息?
答案 0 :(得分:1)
如果没有看到更多您的查询,听起来您应该加入tableC
两次:
SELECT
p.*,
-- more fields?
COALESCE(c1.field1, 'NA') AS field1,
COALESCE(c2.field2, 'NA') AS field2
LEFT JOIN tableC c1
ON c1.id_supplier = P.id_supplier
LEFT JOIN tableC c2
ON c2.id_branch = P.id_branch