Join multiple tables in a ternary

时间:2017-12-03 23:56:40

标签: sql

I have a 3 tables (customers, customerID is PK)(services, serviceID is PK)(equipment, equID is PK). The second two tables have a cost associated with them. All 3 tables connect individually to a table (Billing, transID is the PK). Another process puts transactions in for each customer which charges them for their services individually. I would like to generate a query that pulls all transactions and costs for related equipment and services. When I tried to join cus->billing->service->billing->equip it causes some weirdness. Does anyone know a better way to do this?

Select * from Customer as c 
inner join Billing as b on c.customerID=b.customerID
inner join Service as s on b.ServID=s.ServID
inner join Billing on s.ServID=b.ServID
inner join Equipment as e on b.EquID=e.EquID AND b.Serial=e.Serial
where c.customerID=1

2 个答案:

答案 0 :(得分:1)

虽然您已加入Billing表两次,但您还没有使用第二个。我想你可以从查询中删除以下内容。

inner join Billing on s.ServID=b.ServID --(4th line  of  the  query) 

答案 1 :(得分:0)

我得到了朋友的一些帮助和评论。最终代码如下。

Select * from Customer as c 
inner join Billing as b on c.customerID=b.customerID
left join Service as s on b.ServID=s.ServID
left join Equipment as e on b.EquID=e.EquID AND b.Serial=e.Serial
where c.customerID=1