PostgreSQL:加入另一个表的计数

时间:2014-01-04 07:59:32

标签: sql postgresql join left-join

我有三个表:usersitemsboards

create table users (
    id serial primary key,
    name text
);  

create table items (
    id serial primary key,
    user_id int,
    title text
);  

create table boards (
    id serial primary key,
    user_id int,
    title text
);n

我想选择具有每个用户拥有的项目和板数的所有用户:

select
    users.*,
    count(items) as item_count,
    count(boards) as board_count
from users
    left join items on items.user_id = users.id
    left join boards on boards.user_id = users.id
group by users.id;

不幸的是,这并没有给我正确的数量。计数高于应有的数量。发生了什么,为什么,以及如何解决这个问题?

2 个答案:

答案 0 :(得分:7)

问题是由两个左连接产生重复值的事实引起的。

要解决此问题,您可以只计算不同的值

SELECT u.id, u.name,
       COUNT(DISTINCT i.id) item_count,
       COUNT(DISTINCT b.id) board_count
  FROM users u LEFT JOIN items i
    ON u.id = i.user_id LEFT JOIN boards b
    ON u.id = b.user_id
 GROUP BY u.id, u.name

或单独计算每个用户的项目和板子,然后将其与用户联系

SELECT u.*, 
       COALESCE(i.item_count, 0) item_count, 
       COALESCE(b.board_count, 0) board_count
  FROM users u LEFT JOIN
(
  SELECT user_id, COUNT(*) item_count
    FROM items
   GROUP BY user_id
) i ON u.id = i.user_id LEFT JOIN
(
  SELECT user_id, COUNT(*) board_count
    FROM boards
   GROUP BY user_id
) b ON u.id = b.user_id

这是 SQLFiddle 演示

答案 1 :(得分:3)

我认为这应该可以解决问题

select
    u.*,
    (select count(*) from items where user_id = u.id) as item_count,
    (select count(*) from boards where user_id = u.id) as board_count
from users as u
group by u.id;