K
K
KBBS2021-06-29 10:15:10
PostgreSQL
KBBS, 2021-06-29 10:15:10

How to make a request, if possible?

You must select the 10 highest rated entries from a particular category:

SELECT * FROM `tbl` WHERE `category` = 1 ORDER BY `rating` DESC LIMIT 10;

In this case, if there are no records that meet the condition, or there are not enough of them, then select the records with the highest rating from any category. Basically the same query, but without the WHERE block.

In general, there should be such an algorithm:
If the selection with WHERE gives us 10 records, then we select them and only them.
If there are no records with regard to WHERE, then we take 10 records from any categories.
If, taking into account WHERE, we can get only 4 records, then we take them, and finish off the remaining 6 with records from any categories.
But at the output, we should always get 10 entries sorted by rating.
Is it possible to write this in one request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-06-29
@KBBS

You can use sorting first by category = 1 DESC then by rating DESC

SELECT * FROM tbl 
ORDER BY 
  category = 1 DESC, 
  rating DESC 
LIMIT 10;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question