这个sql的更好版本?
我试图在我的查询中创建一些计数,我的代码一遍又一遍地重新计算总和。有没有更好的书写方法这个sql的更好版本?,sql,Sql,我试图在我的查询中创建一些计数,我的代码一遍又一遍地重新计算总和。有没有更好的书写方法 if( ( ( select count(`t2`.`id`) from `qbinvoices` `t2` where `t2`.`qbAccNumber` = `t1`.`qbAccNumber` and `t2`.`divisionId` = `t1`.`divisionId` )
if(
(
(
select count(`t2`.`id`)
from `qbinvoices` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber`
and `t2`.`divisionId` = `t1`.`divisionId`
) > 0
),
(
select count(`t2`.`id`)
from `qbinvoices_view` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber`
and `t2`.`monthStart` > 0
and `t2`.`divisionId` = `t1`.`divisionId`
),
(
select count(`t2`.`id`)
from `qbestimatesnew_view` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber`
and `t2`.`divisionId` = `t1`.`divisionId`
)
) AS `invoiceItemsCount`
我用的是:
select count(`t2`.`id`)
from `qbinvoices` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber`
and `t2`.`divisionId` = `t1`.`divisionId`
在If
语句中。ie:if(mystatement>0,mystatement,differentiveversionofmystatement)
我也在视图中使用它,所以我不能使用变量。如果在
If
语句中不重复计数三次,有没有办法写入它?没有,因为代码没有重复相同的计数。每个现有计数都会查看不同的数据源(qbinvoices
vsqbinvoices\u视图
vsqbestimatesnew\u视图
),并具有不同的可能结果,因此所有计数都必须在sql代码中使用
您可以改为使用
JOIN
s并结合条件聚合,以一种更易于在SELECT
子句中表达的方式将它们汇总起来,并且可能具有更快的执行计划。但是,我们需要查看整个SQL查询,以向您展示这里的更多内容。我将此逻辑表示为:
(case when exists (select 1
from `qbinvoices` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber` and
`t2`.`divisionId` = `t1`.`divisionId`
)
then (select count(`t2`.`id`)
from `qbinvoices_view` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber` and
`t2`.`monthStart` > 0 and
`t2`.`divisionId` = `t1`.`divisionId`
)
else (select count(`t2`.`id`)
from `qbestimatesnew_view` `t2`
where `t2`.`qbAccNumber` = `t1`.`qbAccNumber` and
`t2`.`divisionId` = `t1`.`divisionId`
)
end) AS `invoiceItemsCount`
count()
是确定记录是否存在的昂贵操作<代码>存在的优点是在第一次匹配记录时停止
其他两个计数来自不同的表
此外,我更喜欢
case
而不是数据特定语法,例如if()
我想到的第一个改进是添加回车符,这样就不需要水平滚动。哪个dbms<代码>SQL只是许多供应商使用的通用语言。