SQL:使用来自两个不同表的计数

Posted

技术标签:

【中文标题】SQL:使用来自两个不同表的计数【英文标题】:SQL: Use count from two different tables 【发布时间】:2013-09-23 09:37:53 【问题描述】:

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

我有三张桌子:

    人 书籍(与peopleserno 上的人相关联) 视频(与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

谢谢。

【问题讨论】:

【参考方案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
SQLFiddle Demo

【讨论】:

【参考方案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

【讨论】:

以上是关于SQL:使用来自两个不同表的计数的主要内容,如果未能解决你的问题,请参考以下文章

SQL 2012 将来自多个表的多个查询与连接和计数合并到一个表中

SQLPlus - 跨多个表的计数函数

Oracle Toad SQL 查询导致 id 计数不一致

教义 - 计算来自不同表的记录

使用 rds-data 增加来自 execute_sql 的 aws lambda 结果计数的 1000 限制或使用不同的包?

SQL 查询 - 两个计数不同的粒度