I have an application in which every news, there are translations into your language. But the problem is that there may not be a translation into a user language, and in this case, I need to choose a "standard (any)" language, but I'm not really good at it yet.
Data:
create table languages(id int, name varchar(255), created_at timestamp);
create table posts(id int, created_at timestamp);
create table post_translations(
id int, post_id int,
language_id int, name varchar(255),
is_default boolean, is_approved boolean,
created_at timestamp);
insert into languages(id, name, created_at) values
('1', 'Russian', '2018-12-28 22:46:35'),
('2', 'English', '2018-12-28 22:46:35');
insert into posts(id, created_at) values
('1', '2018-12-28 22:46:35'),
('2', '2018-12-28 22:46:35');
insert into post_translations(id, post_id, language_id, name, is_default, is_approved) values
('1', '1', '1', 'Russian name - first post', true,true),
('1', '1', '1', 'Russian not moderated name - first post', false,false),
('1', '1', '2', 'English name - first post', false,true),
('1', '2', '2', 'English name - second post',true,true),
('1', '2', '2', 'Russian not moderated name - second post', false,false);
Query:
WITH r AS (
SELECT * FROM post_translations
where is_approved = true and language_id = 1
and post_id in (1,2)
)
SELECT * FROM r
UNION ALL
SELECT * FROM post_translations
where is_approved = true
and post_id in (1,2)
AND NOT EXISTS (
SELECT * FROM post_translations
where is_approved = true and language_id = 1
and post_id in (1,2)
);
Here I try to take translations in Russian for two news, and take a standard ( English ) translation, if Russian is not found, but does not come out...