合并多个表中的数据

时间:2019-03-29 04:11:23

标签: mysql mysqli

我想合并来自4个不同查询的数据 所以这是我的查询

SELECT dinas.dinas_id,dinas_nama, COUNT(sc_user.user_id) as total_user from dinas left JOIN sc_user on dinas.dinas_id=sc_user.dinas_id GROUP by dinas.dinas_id
UNION
SELECT dinas.dinas_id,dinas_nama, COUNT(sc_bidang.bi_id) as total_bidang from dinas left JOIN sc_bidang on dinas.dinas_id=sc_bidang.dinas_id GROUP by dinas.dinas_id
UNION
SELECT dinas.dinas_id,dinas_nama, COUNT(sc_kegiatan.ke_id) as total_kegiatan from dinas left JOIN sc_kegiatan on dinas.dinas_id=sc_kegiatan.dinas_id GROUP by dinas.dinas_id
UNION
SELECT dinas.dinas_id,dinas_nama, COUNT(sc_paket.ke_id) as total_paket from dinas left JOIN sc_kegiatan on dinas.dinas_id=sc_kegiatan.dinas_id left join sc_paket on sc_paket.ke_id=sc_kegiatan.ke_id GROUP by dinas.dinas_id

但结果将是这样

enter image description here

但是我想要这样的结果

dinasid | dinas_nama | total_user | total_bidang | total_kegiatan| total_paket

也许有人可以帮助我合并这些数据?

这是我的小提琴 https://www.db-fiddle.com/f/tgohmvPrFnbNz8VgezbsFA/0

(计数)结果必须像这样 enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

您所有的dinas.dinas_id表示组,因此左连接的总和如下所示:

SELECT dinas.dinas_id,
       dinas_nama,
       COUNT(DISTINCT sc_user.user_id) as total_user,
       COUNT(DISTINCT sc_bidang.bi_id) as total_bidang,
       COUNT(DISTINCT sc_kegiatan.ke_id) as total_kegiatan,
       COUNT(DISTINCT sc_kegiatan.ke_id, sc_paket.pa_id) as total_paket
FROM dinas
LEFT JOIN sc_user on dinas.dinas_id=sc_user.dinas_id
LEFT JOIN sc_bidang on dinas.dinas_id=sc_bidang.dinas_id
LEFT JOIN sc_kegiatan on dinas.dinas_id=sc_kegiatan.dinas_id
LEFT JOIN sc_paket on sc_paket.ke_id=sc_kegiatan.ke_id
GROUP by dinas.dinas_id