我有三个表:页面,附件,页面附件
我有这样的数据:
page ID NAME 1 first page 2 second page 3 third page 4 fourth page attachment ID NAME 1 foo.word 2 test.xsl 3 mm.ppt page-attachment ID PAGE-ID ATTACHMENT-ID 1 2 1 2 2 2 3 3 3
我想在该数字为0时获得每页的附件数量.我尝试过:
select page.name, count(page-attachment.id) as attachmentsnumber from page inner join page-attachment on page.id=page-id group by page.id
我得到这个输出:
NAME ATTACHMENTSNUMBER second page 2 third page 1
我想得到这个输出:
NAME ATTACHMENTSNUMBER first page 0 second page 2 third page 1 fourth page 0
如何获得0部分?
将"内部联接"更改为"左外部联接",这意味着"获取联接左侧的所有行,即使右侧没有匹配的行".
select page.name, count(page-attachment.id) as attachmentsnumber from page left outer join page-attachment on page.id=page-id group by page.name
这是使用子查询的另一种解决方案.
SELECT p.name, ( SELECT COUNT(*) FROM [page-attachment] pa WHERE pa.[PAGE-ID] = p.id ) as attachmentsnumber FROM page p