我正在寻找最佳性能查询来获取关联中不同枚举的计数。
采用以下SQL
CREATE TYPE ITEM_TYPE AS ENUM ('coming', 'new', 'archive');
CREATE TABLE centers
(
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
created_at timestamp without time zone default (now() at time zone 'utc'),
updated_at timestamp without time zone default (now() at time zone 'utc')
);
CREATE TABLE items
(
id SERIAL PRIMARY KEY,
center_id INT NOT NULL REFERENCES centers(id),
item_type ITEM_TYPE NOT NULL,
description TEXT NOT NULL,
created_at timestamp without time zone default (now() at time zone 'utc'),
updated_at timestamp without time zone default (now() at time zone 'utc')
);
我想查询所有“中心”,但我也希望根据item_type枚举返回项目计数。
在下面的示例中,ItemNewCount和ItemArchiveCount与枚举相关。
{
id: 1,
name: 'Center Name',
ItemComingCount: 400,
ItemNewCount: 300,
ItemArchiveCount: 567
}
答案 0 :(得分:1)
只需合并left join, group by and Case
运算符
试试这个
SELECT c.id, c.name,
sum(case when i.item_type = 'coming' then 1 else 0 end) as ItemComingCount,
sum(case when i.item_type = 'new' then 1 else 0 end) as ItemNewCount,
sum(case when i.item_type = 'archive' then 1 else 0 end) as ItemArchiveCount
from centers as c LEFT JOIN items as i ON c.id = i.center_id
group by c.id, c.name