我想联接两个表,
booking table
id from_branch to_branch
1 2 4
2 3 4
Branch Table
id name
1 pune
2 mumbai
3 nanded
4 parbhani
5 aurangabad
如上表所示,我将它们与两个表(from_branch,to_branch)中的公共ID结合在一起
我的查询
SELECT booking.id,
booking.from_branch,
booking.to_branch,
branch.branch_id,
branch.branch_name AS "FROM",
branch.branch_name AS "TO"
FROM booking
JOIN branch
ON booking.from_branch = branch.branch_id
WHERE booking.from_branch = branch.branch_id
OR booking.to_branch = branch.branch_id
我如何获得
这样的结果id from_branch to_branch FROM TO
1 2 4 Mumbai Parbhani
2 3 4 Nanded Parbhani
答案 0 :(得分:2)
左两次进入第二张桌子
SELECT a.*, b.name as 'FROM', c.name as 'TO'
FROM booking a
LEFT JOIN Branch b ON a.from_branch = b.id
LEFT JOIN Branch c ON a.to_branch = c.id
答案 1 :(得分:0)
使用两次与分支表的联接
select b.from_branch,b.to_branch,
bn.name as from_branch_name,
bn1.name as to_branch_name
from booking b join branch bn
on b.from_branch=bn.id
join branch bn1 on b.to_branch=bn1.id