A
A
Albert Ushakov2021-05-23 12:20:27
SQL
Albert Ushakov, 2021-05-23 12:20:27

How to summarize data when it is in sql in one query?

There is a first base with articles and a second one with additional data (Statistics, tags, etc.).
I make a conclusion by rating and there was a problem with query optimization (I don’t even know how to google it).
How to make it so that we do not make additional requests for rating and rating_count and take them out of the postmeta request and use them for counting and sorting?

SELECT * , 
//Тут я вычисляю сам рейтинг для сортировки и как эти данные взять без доп запросов?
(sum(rating.meta_value*rating_count.meta_value)/sum(rating_count.meta_value)) AS rating_sum) 

FROM posts 
//В этом запросе по сути есть данные все, которые нужны
INNER JOIN postmeta ON (posts.ID = postmeta.post_id)

//Но приходится делать еще один запрос, чтобы получить значение рейтинга
INNER JOIN postmeta AS rating
ON ( posts.ID = rating.post_id )

//Здесь запрос на количество поставленных оценок
INNER JOIN postmeta AS rating_count
ON ( posts.ID = rating_count.post_id )

WHERE
//Тут небольшой критерий и по сути поиск значений по ключу
(rating.meta_key = 'post_rating' AND rating.meta_value >= 2) AND 
(rating_count.meta_key = 'post_rating_count' AND rating_count.meta_value > 1)

Postmeta stores data post_id - Article ID, meta_key - Parameter key, meta_value - Parameter value.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question