列出所有表元素和count(),即使count为0

时间:2018-07-17 22:09:53

标签: sql count

假设以下表格:

table book(
  id,
  title,
  deleted
)
table invoice(
  id,
  book_id,
  settled
)

我需要列出所有书籍的清单以及每本书的已结算发票数。

我尝试过:

select book.id, title, count(invoice.id)
from book LEFT OUTER JOIN invoice ON book.id=invoice.book_id
where deleted=0
    and settled=1
group by book.id

仅当一本书至少有一张已结算发票或完全没有任何发票时,此方法才有效。但是,如果某本书尚未结清发票并且没有任何已结清发票,则失败。

有什么想法要查询吗?

2 个答案:

答案 0 :(得分:2)

以下将列出所有帐册,但仅合并并计算已结算的发票。

SELECT 
    b.id, b.title, COUNT(i.id) AS settled
FROM 
    book b
LEFT JOIN invoice i
    ON b.id = i.book_id 
    AND i.settled = 1
WHERE 
    b.deleted = 0
GROUP BY
    b.id

答案 1 :(得分:1)

and settled = 1上的WHERE条件有效地将您的LEFT JOIN变成了INNER JOIN。您可以将CASE表达式添加到COUNT中:

SELECT  b.id, 
        b.title, 
        COUNT(CASE WHEN i.settled = 1 THEN 1 END)
FROM book b
LEFT JOIN invoice i
    ON b.id = i.book_id
WHERE b.deleted=0
GROUP BY b.id;

或者将LEFT JOIN与已过滤的发票表一起使用:

SELECT  b.id, 
        b.title, 
        COUNT(i.id)
FROM book b
LEFT JOIN ( SELECT *
            FROM invoice
            WHERE settled = 1) i
    ON b.id = i.book_id
WHERE b.deleted=0
GROUP BY b.id;