sql triple join:计数上的模糊属性名称

时间:2011-12-15 21:02:45

标签: sql join count

所以我想要计算一些书籍,但这些书籍存储在两个具有相同属性名称的不同表格中。 我想得到一个看起来像的结果:

  name1 [total number of books of 1]
  name2 [total number of books of 2]    

我尝试了这种三连接;

SELECT DISTINCT name, count(book)
FROM writes w
LEFT JOIN person p on p.id = w.author
LEFT JOIN book b on b.title = w.book
LEFT JOIN controls l on l.controller=p.id
GROUP BY name
ORDER BY name DESC

但由于book作为写入和控件中的属性存在,因此无法执行查询。 它只能在我遗漏其中一个连接时才能识别它。

如何告诉sql引擎为每个人计算两个图书属性的数量?

3 个答案:

答案 0 :(得分:2)

由于您感兴趣的数据库设计,您应该发出2个不同的sql,然后将它们合并以处理单个输出。

A)

SELECT DISTINCT w.name as 'Name', count(w.book) as 'Cnt'
FROM writes w
LEFT JOIN person p on p.id = w.author
LEFT JOIN book b on b.title = w.book

B)

SELECT DISTINCT l.name as 'Name', count(l.book) as 'Cnt'
FROM controls l
LEFT JOIN person p on p.id = l.controller
LEFT JOIN book b on b.title = l.book

出于您的目的,您可以获得A和B的UNION。

或者您可以将它们用作第三个SQL的数据源

select A.Name, sum(A.Cnt+B.Cnt) 
from  A,  B 
where A.Name = B.Name
group by A.Name
order by A.Name

答案 1 :(得分:1)

WITH T AS 
( 
  SELECT DISTINCT 'WRITES' FROMTABLE, w.name, w.count(book) 
    FROM writes w
    LEFT JOIN person p on p.id = w.author
    LEFT JOIN book b on b.title = w.book
  GROUP BY name
  UNION ALL 
  SELECT DISTINCT 'CONTROLLS' FROMTABLE, c.name, count(c.book) 
    FROM controlls c
    LEFT JOIN person p on p.id = c.author
    LEFT JOIN book b on b.title = c.book
  GROUP BY name
)
SELECT * FROM T ORDER BY NAME

应该工作。

HTH

答案 2 :(得分:0)

这将根据每个不同作者的ID来处理他们编写的书籍数量。预聚合将为每位作者返回一条记录,其中包含该作者的多少本书。然后,加入人员表获取名称。我通过ID和作者姓名离开它的原因是......如果你有两个作者“John Smith”,但它们各自的ID分别为123和389.你不会希望这些卷起来的相同人(或你)。

select
      P.ID,
      P.Name,
      PreAgg.BooksPerAuthor
   from
      ( select
              w.author,
              count(*) BooksPerAuthor
           from
              writes w
           group by
              w.author ) PreAgg
      JOIN Person P
         on PreAgg.Author = P.id
   order by 
      P.Name