(mysql)子查询返回多行

时间:2014-05-12 08:18:20

标签: mysql

我试图获取总数.of" jml_pddk_miskin"在每个区(" kecamatan")与升序。但是我收到了错误,因为"子查询返回多行"。

这是我的疑问:

select 
mkec.id AS id,mkec.nama AS kecamatan,rpb.tahun AS tahun,
ifnull((select sum(rpb.jml_pddk_miskin) 
        from rekap_penduduk_bps rpb 
        join master_kelurahan mkel on mkel.id = rpb.id_kelurahan 
        where 
        mkel.id_kecamatan = mkec.id 
        and rpb.id_kelurahan = mkel.id 
        group by rpb.id ),0) AS total_miskin 
from master_kecamatan mkec 
join rekap_penduduk_bps rpb 
group by mkec.nama 
order by mkec.id

这是以上查询的结果: result query

我想要这样的结果...... result query

2 个答案:

答案 0 :(得分:0)

你的内心疑问

select sum(rpb.jml_pddk_miskin) 
from rekap_penduduk_bps rpb 
join master_kelurahan mkel on mkel.id = rpb.id_kelurahan 
where 
mkel.id_kecamatan = mkec.id 
and rpb.id_kelurahan = mkel.id 
group by rpb.id

显然返回了多行(通过group by子句)。

答案 1 :(得分:0)

试试这个,

   SELECT mkec.id AS id,mkec.nama AS kecamatan,rpb.tahun AS tahun,IFNULL((SELECT SUM(rpb.jml_pddk_miskin) 
FROM (rekap_penduduk_bps rpb JOIN master_kelurahan mkel ON mkel.id = rpb.id_kelurahan) WHERE 
mkel.id_kecamatan = mkec.id AND rpb.id_kelurahan = mkel.id GROUP BY rpb.id HAVING rpb.id_kelurahan = mkel.id ),0)
 AS total_miskin FROM master_kecamatan mkec JOIN rekap_penduduk_bps rpb ON mkec.id= rpb.id_kelurahan GROUP BY mkec.nama ORDER BY mkec.id