我有三个子查询,分别给我表a,b,c。我想先加入他们,然后选择必要的信息。我是SQL的新手,不确定我的联接是否是最好的方法:
这是我到目前为止所做的
select
a.truck,
a.vendor,
a.domicile,
b.routes,
c.status
from
(select
Transp.truck
Transp.vendor
Transp.docimicle
from
Transp) a
left join
(select
Dispatch.truck
count(Dispatch.routes) as routes
from
Dispatch
group by
Dispatch.truck) b on a.truck = b.truck
left join
(select
Repair.truck
Repair.status
from
Repair) c on a.truck = c.truck
答案 0 :(得分:3)
您可以删除当前拥有的至少两个子查询:
SELECT
t.truck,
t.vendor,
t.domicile,
COALESCE(b.routes, 0) AS routes,
r.status
FROM Transp t
LEFT JOIN
(
SELECT truck, COUNT(*) AS routes
FROM Dispatch
GROUP BY truck
) b
ON t.truck = b.truck
LEFT JOIN Repair r
ON t.truck = r.truck;
我说“至少”两个子查询,因为也有可能根本不使用子查询来计算计数。但是,我倾向于按上面的方式编写它,因为它明确表明您正在对Dispatch表进行聚合。