使用组合三个表的计数子选择查询

时间:2018-02-02 09:11:15

标签: mysql

我有三个mysql表。 notification_tblsection_tbluser_plant_tbl

user_plant_tbl植物,一个植物可能在section_tbl表中有多个部分notification_tbl已通过部分全部关闭并打开通知。我想要的是从notification_tbl表中获取所有关闭通知的所有部分(例如:部分名称)计数特别是部分

section_tbl

section_id      plant
sectionX        2400
sectionY        2400

user_plant_tbl

user_id  plant
3001     2400
3003     2200

notification_tbl

notification_id    plant   section_id      open_flag
60000062           2400    sectionX        x
60000063           2400    sectionX        x
60000064           2400    sectionX        x
60000063           2400    sectionY        x
60000064           2400    sectionY        x

例如,让我们看到 sectionX notification_tbl表格中有 3 已关闭的通知行, sectionY 2 STRONG>。然后我想得到一个输出,

sectionX 3
sectionY 2

这是我使用的查询,但它并没有给我所需的输出。

SELECT DISTINCT
    a.section_id,
    (SELECT count(section_id) FROM notification_tbl WHERE open_flag = 'x') AS countx
FROM
    section_tbl AS a
INNER JOIN user_plant_tbl AS b ON a.plant = b.plant
WHERE
    b.user_id = 3001
    AND b.plant = 2400
    AND a.division = 7
GROUP BY
    a.section_id
ORDER BY
    countx DESC;

1 个答案:

答案 0 :(得分:3)

根据您的示例,section_id中也有一个notification_tbl列,因此您可以将section_tblnotification_tbl关联在该列上。以下查询给出了答案:

SELECT
    s.section_id,
    COUNT(n.section_id) AS count_closed
FROM section_tbl AS s
INNER JOIN notification_tbl AS n ON n.section_id = s.section_id
INNER JOIN user_plant_tbl AS u ON s.plant = u.plant
WHERE
    u.user_id = 3001
    AND u.plant = 2400
    AND s.division = 7
    AND n.open_flag = 'X'
GROUP BY
    s.section_id
ORDER BY
    count_closed DESC;

<强> 更新

根据您的评论我修改了查询以获得这些结果。

SELECT
    s.section_id,
    SUM(case when n.open_flag = 'X' then 1 else 0 end) AS count_closed,
    SUM(case when n.open_flag <> 'X' then 1 else 0 end) AS count_opened 
FROM section_tbl AS s
INNER JOIN notification_tbl AS n ON n.section_id = s.section_id
INNER JOIN user_plant_tbl AS u ON s.plant = u.plant
WHERE
    u.user_id = 3001
    AND u.plant = 2400
GROUP BY
    s.section_id
ORDER BY
    count_closed DESC;

请参阅 DEMO

然后考虑尚未打开或关闭状态标志的新插入部分。

SELECT
    s.section_id,
    SUM(CASE WHEN n.open_flag = 'X' THEN 1 ELSE 0 END) AS count_closed
FROM section_tbl AS s
LEFT JOIN notification_tbl AS n ON s.section_id = n.section_id
INNER JOIN user_plant_tbl AS u ON s.plant = u.plant
WHERE
    u.user_id = 3001
    AND u.plant = 2400
GROUP BY
    s.section_id
ORDER BY
    count_closed DESC;

<强> DEMO

相关问题