2

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

我有三张桌子:

  1. 人们
  2. 书籍(与人相关联peopleserno
  3. 视频(与 上的人相关联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

谢谢你。

4

5 回答 5

4

您需要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 演示

于 2013-09-23T09:40:52.600 回答
1

除非表上存在 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
于 2013-09-23T09:45:42.477 回答
1
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
于 2013-09-23T09:41:20.330 回答
0

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

于 2013-09-23T09:41:08.497 回答
0
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
于 2013-09-23T10:44:21.653 回答