如何通过在mysql中使用join来获取数据

时间:2017-12-26 02:14:53

标签: mysql database join

我有一张桌子:

enter image description here

和这张表:

enter image description here

我想创建像这样的报告

enter image description here

我试过这个SQL:

select
    master_problem.problem,
    master_problem.sop_reference,
    master_problem.adidas_spec,
    count(log_roving_qc.id_problem) as jumlahfrom
master_problem
inner join log_roving_qc
    on master_problem.id_problem = log_roving_qc.id_problem
group by master_problem.id_problem

但空数据未显示。我想显示描述为0

的空白数据

1 个答案:

答案 0 :(得分:2)

master_problem表左连接到执行计数聚合的子查询:

SELECT
    mp.problem,
    mp.sop_reference,
    mp.adidas_spec,
    COALESCE(t.cnt, 0) AS jumlahfrom
FROM master_problem mp
LEFT JOIN
(
    SELECT id_problem, COUNT(*) as cnt
    FROM log_roving_qc
    GROUP BY id_problem
) t
    ON mp.id_problem = t.id_problem;