SQL多个表,如果没有记录则显示

时间:2017-10-05 07:49:15

标签: mysql sql left-join

我有4个表(工作人员,组,部门,办公室),并希望有一个SQL查询可以返回报告(报告)。

    Table: Workers
    +------------+----------+--------------+
    | workers_id | group_id | workers_name |
    +------------+----------+--------------+

    Table: Group
    +------------+------------+---------+-----------+
    | group_id   | group_name | dept_id | office_id |
    +------------+------------+---------+-----------+

    Table: Department
    +---------+----------+-----------+
    | dept_id | dept_name| office_id |
    +---------+----------+-----------+

    Table: Office
    +-----------+------------+
    | office_id | office_name|
    +-----------+------------+

我设法使用以下SQL语句,它会给我结果A:

    SELECT department.dept_name, count (workers.workers_id) as headcount,
    FROM workers, group, department
    WHERE workers.workers_id = group.group_id
    AND group.dept_id = department.dept_id
    GROUP BY group.group_id

    Result A: 
    +------------+----------+
    | dept_name  | headcount|
    +------------+----------+
    | dept A     | 2        |
    +------------+----------+
    | dept B     | 1        |
    +------------+----------+
    | dept D     | 2        |
    +------------+----------+
    | dept F     | 3        |
    +------------+----------+
然而,它没有上市部门有0个工人(因为没有任何意义)。是否仍然可以执行单个查询以获得以下结果?

    Result: 
    +------------+----------+
    | dept_name  | headcount|
    +------------+----------+
    | dept A     | 2        |
    +------------+----------+
    | dept B     | 1        |
    +------------+----------+
    | dept C     | 0        |
    +------------+----------+
    | dept D     | 2        |
    +------------+----------+
    | dept E     | 0        |
    +------------+----------+
    | dept F     | 3        |
    +------------+----------+

我已经尝试过isnull,左连接和联合而没有任何运气,我的sql-fu处于基本级别。非常感谢任何帮助。干杯!

3 个答案:

答案 0 :(得分:1)

由于你想要部门的工作人员,我认为你的意思是按dept_id进行分组(否则COUNT会按工作人员计算工人数,而不是部门。这会导致错误的结果而不是一个部门的一个小组)。另外我想workers.workers_id = group.group_id上的联接并非意图:

SELECT d.dept_name, COUNT(w.workers_id) AS headcount
    FROM Workers w
      JOIN Grp g ON w.group_id = g.group_id
      RIGHT JOIN Department d ON g.dept_id = d.dept_id
    GROUP BY d.dept_id;

NULL workers_id 将不会在COUNT中考虑。

注意:请勿将表格命名为关键字(GROUP)。

答案 1 :(得分:0)

我认为以下查询是您想要的。您可以保留结果集中的每个部门,即使它没有人头数,也可以通过从部门表左侧连接到按部门查找人数的子查询(如果该部门存在)来保留。

SELECT
    d.dept_id,
    d.dept_name,
    d.office_id,
    COALESCE(t.cnt, 0) AS headcount
FROM Department d
LEFT JOIN
(
    SELECT t1.dept_id, COUNT(*) AS cnt
    FROM `Group` t1
    INNER JOIN Workers t2
        ON t1.group_id = t2.group_id
    GROUP BY t1.dept_id
) t
    ON d.dept_id = t.dept_id;

答案 2 :(得分:0)

SELECT dept_name,
IF(count(workers_id) >0 ,count(*),0) AS headcount
FROM workers, group, department
WHERE workers.workers_id = group.group_id
AND group.dept_id = department.dept_id
GROUP BY group.group_id;

您可以使用IF语句, IF语句的语法是..

IF(Condetion,如果结果为true,则结果为false)