PostgreSQL:计数为

时间:2016-04-29 10:43:54

标签: sql postgresql function join plpgsql

我有以下表格:

  • 文库
  • librairies_books

以下内容:

  • librarylibraries_books中有很多书。
  • book可以通过表属于许多库 libraries_books

我需要显示库统计信息:

Name, Number of copies, Number of books

因此,如果图书馆有3本Book-1副本和4本Book-2副本,则应显示统计数据

"Library 1", 7, 2

7 is the number of total copies
2 is the number of books

这是当前的功能,但它不会返回有效的书籍数量。

create or replace function listing()
returns table (
  "ID" int,
  "NAME" varchar,
  "NUMBER OF COPIES" bigint,
  "NUMBER OF BOOKS" bigint) as $$
begin
  return query
    select libraries.id, libraries.name, count(libraries_books.id), count(books.id)
    from libraries
    left join libraries_books
    on libraries.id = libraries_books.library_id
    left join books
    on libraries_books.book_id = books.id
    group by books.id, libraries.id;
end;
$$ language plpgsql;

1 个答案:

答案 0 :(得分:0)

你想要count(distinct)。此外,使用表别名使查询更容易编写和阅读:

select l.id, l.name, count(distinct l.id), count(b.id)
from libraries l left join
     libraries_books lb
     on l.id = lb.library_id left join
     books b
     on lb.book_id = b.id
group by l.id, l.name;

您还需要修复group by,因此它不包含图书ID。