【问题标题】:如何通过组合来自 3 个不同表的数据获得如下输出
【发布时间】:2022-01-20 12:28:33
【问题描述】:

所以我的数据库中有 3 个表,其中所有 3 个表都包含一个具有相似数据的列,但是所有 3 个表中该列的名称都不同,下面是一个示例。

禁止表

user_id ban_user_id ban_date reason end_date
1300 1 xyz xyz xyz
32 1 xyz xyz xyz
43 2 xyz xyz xyz

报告表

user_id last_modified_user_id report_date reason end_date
1300 1 xyz xyz xyz
32 2 xyz xyz xyz
43 2 xyz xyz xyz

警告表

user_id warning_user_id warning_date reason end_date
1300 1 xyz xyz xyz
32 2 xyz xyz xyz
43 3 xyz xyz xyz

现在我想通过组合这3个表来获取数据,其中ban_user_id、last_modified_user_id和warning_user_id包含采取行动的员工的数据,所以我想按员工id对数据进行分组。

我要找的输出如下:

staff_id total_reports total_bans total_warnings
1 1 2 1
2 2 1 1
3 0 0 1

它通过将第二列、ban_user_id、last_modified_user_id、warning_user_id 分别分组来计算每个表的数据。而不是合并数据。

我尝试了 UNION All 之类的东西,但没有成功。

提前感谢您的帮助

【问题讨论】:

    标签: mysql sql group-by count union


    【解决方案1】:

    对所有 3 个表使用 UNION ALL,然后聚合:

    SELECT staff_id,
           COUNT(report) AS total_reports,
           COUNT(ban) AS total_bans,
           COUNT(warning) AS total_warnings
    FROM (
      SELECT last_modified_user_id AS staff_id, 1 AS report, null AS ban, null AS warning FROM Reports
      UNION ALL
      SELECT ban_user_id, null, 1, null FROM Ban
      UNION ALL
      SELECT warning_user_id, null, null, 1 FROM Warning
    ) t
    GROUP BY staff_id;
    

    或者:

    SELECT staff_id,
           SUM(report) AS total_reports,
           SUM(ban) AS total_bans,
           SUM(warning) AS total_warnings
    FROM (
      SELECT last_modified_user_id AS staff_id, 1 AS report, 0 AS ban, 0 AS warning FROM Reports
      UNION ALL
      SELECT ban_user_id, 0, 1, 0 FROM Ban
      UNION ALL
      SELECT warning_user_id, 0, 0, 1 FROM Warning
    ) t
    GROUP BY staff_id;
    

    请参阅demo

    【讨论】:

    • 哇,完美运行,非常感谢。你能帮我理解一下吗,比如这个 0, 1 的东西是如何处理 select 语句的。
    • @VivekBora 联合表的每一行每列包含 0 或 1。看看这个:dbfiddle.uk/… 然后将这些行相加。
    【解决方案2】:

    您可以使用Table joins (Inner/outer/left/right) 来获取数据而不是联合。 我假设 staff_id 相当于 user_id 列,因为您没有提及任何相关内容,因此您的脚本将如下所示:

    SELECT W.user_id AS staff_id, 
        B.ban_user_id, 
        R.last_modified_user_id, 
        W.warning_user_id
    FROM Warning AS W
    LEFT JOIN Reports AS R on R.user_id = W.user_id
    LEFT JOIN Ban AS B on B.user_id = W.user_id
    group by W.user_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-18
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多