Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在几列旁边计数_Sql_Performance_Oracle_Conventions - Fatal编程技术网

Sql 在几列旁边计数

Sql 在几列旁边计数,sql,performance,oracle,conventions,Sql,Performance,Oracle,Conventions,所以我只是想知道是否有一种更有效的查询db的方法,其中: 我加入了几张桌子, 我从每个表中选择大约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

所以我只是想知道是否有一种更有效的查询db的方法,其中: 我加入了几张桌子, 我从每个表中选择大约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

我只是在想,一定有更好的方法来获取此查询中的纠正措施计数,而不必从其他每一列中获取最大值,对吗?

您可以将它们放在
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;

但是,这可能不会对性能产生太大影响。

您可以在内联视图中进行计数。性能的缺点是,您将对
差异表进行两次扫描

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;

这些表的主键是
d.discrepancyid
a.autoid
吗?如果是这样,那么看起来
max
聚合没有取得任何效果,您可以将这些列添加到
groupby
中。或者这会产生不同的结果,如果是这样的话,原因是什么?除了允许查询运行之外,他们不会做任何事情,他们会按照Gordon Linoff的建议进入组中,因为至少看起来更干净