所以我只是想知道是否有一种更有效的查询数据库的方法: 我要加入几张桌子, 我从每张桌子中选择大约5个左右的列, 从其中一个表中,我只是计算与每个差异相关的纠正措施的数量。
类似于:
select D.discrepancyID, MAX(D.discrepancyComment), MAX(A.make), MAX(A.model), Count(CA.CorrectiveActionID)
from Discrepancy D
left join Automobile A on A.autoID = D.autoID
left join CorrectiveActions CA on CA.discrepancyID = D.discrepancyID
group by D.discrepancyID
我只是认为必须有一种更好的方法可以在此查询中获取纠正操作计数,而不必从其他每列中获取最大值,我是对的吗?
答案 0 :(得分:1)
您可以将这些内容放在group by
子句中:
select D.discrepancyID, D.discrepancyComment, A.make, A.model, Count(CA.CorrectiveActionID)
from Discrepancy D left join
Automobile A
on A.autoID = D.autoID left join
CorrectiveActions CA
on CA.discrepancyID = D.discrepancyID
group by D.discrepancyID, D.discrepancyComment, A.make, A.model;
但是,这可能不会对性能产生太大影响。
答案 1 :(得分:0)
您可以在内联视图中执行计数。性能的缺点是您正在扫描Discrepancy
表两次。
select D.discrepancyID, D.discrepancyComment, A.make, A.model, CorrectiveActionCounts.Count_CorrectiveAction
from Discrepancy D
INNER JOIN
(SELECT
D.discrepancyID AS discrepancyID,
Count(CA.CorrectiveActionID) AS Count_CorrectiveAction
from Discrepancy D
LEFT JOIN CorrectiveActions CA on CA.discrepancyID = D.discrepancyID
GROUP BY D.discrepancyID
) CorrectiveActionCounts
ON CorrectiveActionCounts.discrepancyID = D.discrepancyID
LEFT JOIN Automobile A on A.autoID = D.autoID;