加入 3 tables 而不会失去推荐每个 table 的能力

Join 3 tables without losing ability to refer each table

我有 3 table 个模拟数据

Item *id, name*
1, coke
2, fanta 
3, juice

Branch *id, name*
1, store
2, warehouse
3, shop

BranchItem *item_id, branch_id, qty*
1, 1, 100
1, 2, 30
2, 2, 10

我想查询一个项目(例如可乐)并在所有分支中获取它的数量(即使它不存在的那些,那些应该有 NULL for qty列)

所以结果应该是这样的

1, coke, store, 100

1, coke, warehouse, 30

1, coke, shop, NULL

我有一个查询可以执行此操作,但由于别名 table,我无法引用结果 table 的列。结果的解析在 ORM 对象中完成,最好不要重写

我的查询

Select * from item left join (select * from branch left join ( select * from branchitem where item_id = 1) branchitem on branch.id = branchitem.branch_id) JOINEDNAME on true where item.id = 1;

我的问题是我不想让 Elias 加入分支和早午餐项,因为我无法在 ORM 中单独引用它们。如何重写此查询以使 table 保留其名称?

您不需要使用子查询:

SELECT Item.id,
       Item.name,
       Branch.name,
       BranchItem.qty
FROM Item
CROSS JOIN Branch
LEFT JOIN BranchItem ON Item.id = BranchItem.item_id
                    AND Branch.id = BranchItem.branch_id
WHERE Item.id = 1;  -- or put it into the branch join