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);
I need to select sections based on requested section_version.version_name.
If the version_name is "default", then query just need to return all sections which have "default" version.
But if the "version A" was requested, then it should return every section that belongs to "version A", and add a missing sections from "default" version - basing on section_name.
Please see this fiddle: http://sqlfiddle.com/#!15/466e1/1/0
Here's what I came up with:
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'
;
This is probably a naive try, so I am looking for a better solution.
It would be nice to have one query that will handle:
- Selecting only "default"
- Selecting a specific version
- Working when no default version exists (f.i. like Instruments)