V
V
Valeriu Vodnicear2019-06-05 14:07:48
PostgreSQL
Valeriu Vodnicear, 2019-06-05 14:07:48

What is the best way to write SELECT for product translations?

there is a table productand product_translate
for one product there are translations in several languages,
we need to select a language that the user understands better (there is one id) if there is no such translation, then we select any other
, this is all in one query
, how best to write?
product_translate:
5cf7a26aab2aa671083287.png
you can use subqueries, but you will have to write 2 subqueries, 1 for title, 2 for description
and it's still not clear how to write ORDER BYin subqueries

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2019-06-05
@melkij

select ...
from product as p
join lateral (
select title, description from product_translate as pt
where pt.product_id = p.id order by language_id = ? limit 1
) on true
where ....

As usual, I could confuse the sorting direction - add desc if there is a translation, but it is not selected.
The idea of ​​choosing any other language in the absence of the right one is strange. But that's exactly what I wrote.
If there are no translations at all, now such a product will not be displayed. If needed with NULL instead of text - replace join with left join.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question