create table sections(
id serial,
section_name char(255) not null,
version_id int not null
);
create table section_versions(
id int primary key not null,
version_name char(255) not null
);
insert into section_versions(id, version_name)
values (1, 'default'), (2, 'version A'), (3, 'version B');
insert into sections(section_name, version_id)
values ('Toys', 1), ('Animals', 1), ('Cars', 1),
('Toys', 2), ('Animals', 2), ('Instruments', 2),
('Toys', 3);
我需要根据请求的 section_version.version_name 选择sections。
如果version_name是"default",那么查询只需要返回所有sections有"default"强>版本。
但如果请求的是"version A",那么它应该返回属于"version A"的每个section,并添加“默认” 版本中缺少部分 - 基于 section_name。
请看这个 fiddle : http://sqlfiddle.com/#!15/466e1/1/0
这是我想出的:
select * from sections
join section_versions on (section_versions.id = sections.version_id)
where section_versions.version_name = 'default'
and sections.section_name not in (
select sections.section_name from sections
join section_versions on (section_versions.id = sections.version_id)
where section_versions.version_name = 'version A'
)
UNION
select * from sections
join section_versions on (section_versions.id = sections.version_id)
where section_versions.version_name = 'version A'
;
这可能是一次天真的尝试,所以我正在寻找更好的解决方案。
如果有一个查询可以处理:
- 仅选择“默认”
- 选择特定版本
- 在不存在默认版本时工作(例如 Instruments)
最佳答案
如果我正确理解了您的意图,那么以下查询应该会有所帮助:
select distinct on (sections.section_name) *
from sections
join section_versions on (section_versions.id = sections.version_id)
where
section_versions.version_name in ('default', 'version A')
order by
sections.section_name,
case version_name
when 'default' then 1
else 0
end;
有关详细信息,请参阅 http://www.postgresql.org/docs/current/static/sql-select.html 中的“DISTINCT 子句”段落
关于sql - 简化覆盖重复行的 UNION 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28096029/