Skip to content
Advertisement

how to show all result query even though the results are empty

I count my data from database, but I have a problem with the result. the result only displays data that is not empty, while the empty data is not displayed. how do I display data rows that are empty and not empty?

the result of my query like this

pendidikan| Male | Famale | Total
----------+------+--------+------
    SD    |  3   |   4    |  7
   SMP    |  2   |   1    |  3
   SMA    |  1   |   3    |  4
    S1    |  10  |   1    |  11

BUT i want the result like this :

pendidikan| Male | Famale | Total
----------+------+--------+------
    SD    |  3   |   4    |  7
   SMP    |  2   |   1    |  3
   SMA    |  1   |   3    |  4
    S1    |  10  |   1    |  11
    S2    |  0   |   0    |  0
    S3    |  0   |   0    |  0

i want to show empty data from my database. this is my query

SELECT a.NamaStatusPendidikan, COUNT(c.IDPencaker) as total,
count(case when c.JenisKelamin='0' then 1 end) as laki,
count(case when c.JenisKelamin='1' then 1 end) as cewe 
FROM msstatuspendidikan as a JOIN mspencaker as c ON
a.IDStatusPendidikan = c.IDStatusPendidikan JOIN 
mspengalaman as d ON c.IDPencaker = d.IDPencaker 
WHERE d.StatusPekerjaan = '0' AND c.RegisterDate 
BETWEEN '2019-01-01' AND '2019-03-01' GROUP BY a.IDStatusPendidikan

Advertisement

Answer

Try running this query:

SELECT sp.NamaStatusPendidikan, 
       COUNT(*) as total,
       SUM( p.JenisKelamin = 0 ) as laki,
       SUM( p.JenisKelamin = 1 ) as cewe 
FROM msstatuspendidikan sp LEFT JOIN
     mspencaker p
     ON sp.IDStatusPendidikan = p.IDStatusPendidikan AND
        p.RegisterDate BETWEEN '2019-01-01' AND '2019-03-01' LEFT JOIN 
     mspengalaman g
     ON g.IDPencaker = c.IDPencaker AND
        g.StatusPekerjaan = 0
GROUP BY sp.IDStatusPendidikan;

Notes:

  • The JOINs have been replaced with LEFT JOINs.
  • Filtering conditions on all but the first table have been moved to the ON clauses.
  • This replaces the meaningless table aliases with table abbreviations, so the table is easier to read.
  • Things that looks like numbers probably are numbers, so I removed the single quotes.
  • This simplifies the counts, using the fact that MySQL treats booleans as numbers in a numeric context.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement