编辑
是否最好将所有查询合并到 1 个单个选择中,例如 select (select...) as q1, (select...) as q2
结束编辑
我需要对一年中的每个月运行相同的以下查询。
每个查询之间的区别仅在于添加group by
或删除单个条件。
第一次查询:我需要计算完成的总访问次数
SELECT
count(*)
from
visit
where
visit_status='Active'
AND
month(visit.date_of_visit)=month(:selectedDate)
AND
year(visit.date_of_visit)=year(:selectedDate)
当然:selectedDate
将通过PHP中的绑定(bind)值来设置。
第二个查询:是关于计算患者数量(而不是访问次数),只需添加 group by Visit.patent_id
SELECT
count(*)
from
visit
where
visit_status='Active'
AND
month(visit.date_of_visit)=month(:selectedDate)
AND
year(visit.date_of_visit)=year(:selectedDate)
group by visit.patient_id
然后我将使用 rowCount
来获取结果,因为返回值是由 group by
产生的行。
应该重复相同的查询,但现在没有日期,这意味着从第一次在系统上注册数据开始计数:
SELECT
count(*)
from
visit
where
visit_status='Active'
group by visit.patient_id
我使用以下方法没有遇到错误,但是有没有更好的方法来做到这一点并通过最小化查询数量来减少服务器上的负载?
最佳答案
试试这个。
select COUNT(distinct (visit.patient_id)) from visit where visit_status='Active'
关于mysql - 当我们需要在条件略有变化的情况下多次运行相同的查询时,如何减少服务器上的负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50810171/