A
A
alex4answ2019-12-15 16:04:21
SQL
alex4answ, 2019-12-15 16:04:21

Get string with maximum match?

We need to get a list of movie descriptions for the current language and "site"
There is a movie_desc table:
id | movie_id | text | site_id | lang
There is a query:

SELECT * FROM `movie` where ( site_id = 15 OR site_id = 1 OR site_id IS NULL) AND ( lang = 'ru' OR lang = 'en' OR lang IS NULL)

The query returns almost all occurrences (which is understandable, because site_id, lang can be NULL)
How can I return 1 row with the highest match for each movie?
I thought to use GROUP BY by movie_id, but this is not an aggregated field.
PS The essence of this perversion:
There are films, but there are descriptions for them in different languages, some films do not have descriptions for some language, and should be displayed either for the standard language (lang en) or a general description (lang IS NULL)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Game Master, 2019-12-15
@baitarakhov

select *
from (
         select movie_desc.*,
                row_number()
                        over (partition by movie_id order by domain_id desc) as rn_domain,
  		row_number()
                        over (partition by movie_id order by language_id desc) as rn_lang
         from movie_desc
     ) x
where x.rn_domain = 1 and x.rn_lang = 1;

https://www.db-fiddle.com/f/ipkTSyKiavc4oQ8iRPTKN6/0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question