在mysql查询中的位置和优先级

时间:2015-03-30 14:26:49

标签: php mysql

我在这个查询中遇到了近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

有关如何指定同一条款中的具体和位置的任何帮助?

1 个答案:

答案 0 :(得分:1)

尝试如下;通过使用适当的分组获取所需列的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