【问题标题】:SQL: Use count from two different tablesSQL:使用来自两个不同表的计数
【发布时间】:2023-03-31 11:10:02
【问题描述】:

如何为以下场景构造查询:

我有三张桌子:

  1. 书籍(与peopleserno 上的人相关联)
  2. 视频(与peopleserno 上的人相关联)

我想创建一个 SQL,其中输出给出一行,其中包含特定人阅读/观看的书籍和视频的数量。

示例输出:

John | 3 (books) | 2 (videos)

我尝试过这样的事情,但它不起作用:

select a.name, 
       count(b.serno) as books, 
       count(c.serno) as videos
  from people a, 
       books b, 
       videos c
 where a.serno = b.peopleserno
   and a.serno = c.peopleserno

谢谢。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您需要 left join 来获取甚至没有阅读/观看任何内容的用户,然后您需要 group by 用户来获取特定的用户数

    select a.name, 
           count(distinct b.title) as books, 
           count(distinct c.title) as videos 
    from people a
    left join books b on a.serno = b.peopleserno
    left join videos c on a.serno = c.peopleserno
    group by a.name
    

    SQLFiddle demo

    【讨论】:

    • @491243:你说得对,我没有。现在修复了错误。谢谢。
    • 实际上,如果该列上设置了标识并且您可以正确计数,则它会起作用,例如COUNT(DISTINCT x.identityColumn):)
    【解决方案2】:
    select a.name, 
           ( select count(b.serno) from books b where a.serno = b.peopleserno ) as books, 
           ( select  count(c.serno) from videos c where a.serno = c.peopleserno) as videos 
    from people a
    

    【讨论】:

      【解决方案3】:

      除非表上存在 auto_incremented 列,否则在子查询中进行计算是安全的。假设表没有 auto_incremented 列,

      SELECT  a.Name,
              COALESCE(b.TotalBook, 0) TotalBook,
              COALESCE(c.TotalVideo, 0) TotalVideo
      FROM    People a
              LEFT JOIN
              (
                  SELECT  peopleserno, COUNT(*) TotalBook
                  FROM    Books
                  GROUP   BY peopleserno
              ) b ON a.serno = b.peopleserno
              LEFT JOIN
              (
                  SELECT  peopleserno, COUNT(*) TotalVideo
                  FROM    Videos
                  GROUP   BY peopleserno
              ) c ON a.serno = c.peopleserno
      

      【讨论】:

        【解决方案4】:

        您必须对需要汇总的字段使用 GROUP BY 子句才能计数。

        【讨论】:

          【解决方案5】:
          select a.name, 
                 count(b.title)||' (books)'  as books, 
                 count(c.title)||' (videos)'  as videos 
          from people a
          left join books b on a.serno = b.peopleserno
          left join videos c on a.serno = c.peopleserno
          group by a.name
          
          
          OR
          
          select a.name, 
                 ( select count(b.serno) from books b where a.serno = b.peopleserno ) as books, 
                 ( select  count(c.serno) from videos c where a.serno = c.peopleserno) as videos 
          from people a
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-02-11
            • 1970-01-01
            • 2018-04-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多