其中和在mysql查询中具有优先级


where and having precedence in mysql query

我在这个查询中遇到了将近3个小时的问题,到目前为止,谷歌搜索对我没有任何帮助:

select id,nombres,apaterno,amaterno, (select sum(cargo) from tb_consultorios_recibos_transacciones where id_paciente = tb_consultorios_pacientes.id and date(fecha_trans)>='2015-03-01' and date(fecha_trans)<='2015-03-31') as cargospaciente, (select sum(abono) from tb_consultorios_recibos_transacciones where id_paciente = tb_consultorios_pacientes.id and date(fecha_trans)>='2015-03-01' and date(fecha_trans)<='2015-03-31') as abonospaciente from tb_consultorios_pacientes where id_consultorio = 3 order by apaterno asc, cargospaciente desc

除了where子句之外,我只想显示别名cargospaciente或abonospaciente大于0的行,这是我正在尝试的查询,显然不起作用:

select id,nombres,apaterno,amaterno, (select sum(cargo) from tb_consultorios_recibos_transacciones where id_paciente = tb_consultorios_pacientes.id and date(fecha_trans)>='2015-03-01' and date(fecha_trans)<='2015-03-31') as cargospaciente, (select sum(abono) from tb_consultorios_recibos_transacciones where id_paciente = tb_consultorios_pacientes.id and date(fecha_trans)>='2015-03-01' and date(fecha_trans)<='2015-03-31') as abonospaciente from tb_consultorios_pacientes where id_consultorio = 3 having (cargospaciente>0 or abonospaciente>0)  order by apaterno asc, cargospaciente desc

关于如何在同一条款中指定haven和where,有什么帮助吗?

不如像下面这样尝试;通过正确分组获得所需列的sum,然后将该结果集与外部选择结果连接

select tcp.id,
tcp.nombres,
tcp.apaterno,
tcp.amaterno, 
tab.sum_cargo,
tab.sum_abono
from tb_consultorios_pacientes  tcp
join
(
select id_paciente, sum(cargo) as sum_cargo, sum(abono) as sum_abono
from tb_consultorios_recibos_transacciones 
where date(fecha_trans)>='2015-03-01' 
and date(fecha_trans)<='2015-03-31'
group by id_paciente
having sum_cargo > 0 or sum_abono > 0
) tab
on tcp.id = tab.id_paciente
where tcp.id_consultorio = 3 
order by tcp.apaterno asc, tcp.cargospaciente desc