K
K
KarambiG2021-07-05 22:37:45
MySQL
KarambiG, 2021-07-05 22:37:45

What is the required mysql query for the random post generator by rating?

Please tell me how to generate RANDOM posts based on their ratings?
For example, I have 1000 posts, one RANDOM post should be displayed on the page from the database, while the one with the higher rating has more chances to be displayed on the page.

As far as I understand, Tik-Tok, Instagram, YouTube, etc. work according to this principle. I want to do something similar in terms of logic.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-07-05
@Akina

Well, sort of.

WITH cte AS (
    SELECT *, SUM(rating) OVER (ORDER BY id) cum_rating
    FROM table
)
SELECT
FROM cte t1
JOIN (SELECT RAND() * MAX(cum_rating) rnd_rating
      FROM cte) t2 ON t2.rnd_rating BETWEEN t1.cum_rating - t1.rating AND t1.cum_rating

Really, of course, not BETWEEN, but two inequalities, on the upper bound - strict.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question