A
A
Albert Ushakov2020-09-21 01:20:08
MySQL
Albert Ushakov, 2020-09-21 01:20:08

How to calculate what is the record in the mysql database, subject to sorting?

I'm doing the top and I'm a little stupor with one task.
Here is the main query

SELECT ID, (pm.meta_value+0) AS reating
  FROM $wpdb->posts p
    LEFT JOIN $wpdb->postmeta pm ON (pm.post_id = p.ID)
  WHERE pm.meta_key = 'reating_num' 
    AND p.post_type = 'book'
    AND p.post_status = 'publish'
  ORDER BY reating DESC

Conclusion
Array ( [0] => stdClass Object ( [ID] => 349 [reating] => 21 ) [1] => stdClass Object ( [ID] => 593 [reating] => 0 ) )

In the code, entries are displayed taking into account the number of ratings, whoever has more is higher. But how to calculate what specific place a record is in the top by adding the record ID and its rating?
Not the record ID, but to count how many records were before the desired one, which was found by the condition

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Albert Ushakov, 2020-09-21
@fuck_ask

My version, but it does not count exactly, because of the criterion. Not sure about performance.

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta
ON (wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1
ON ( wp_posts.ID = mt1.post_id )
INNER JOIN wp_postmeta AS mt2
ON ( wp_posts.ID = mt2.post_id )
WHERE 1=1
AND ( wp_postmeta.meta_key = '_wpcr_rating_stars_count'
AND mt1.meta_key = '_wpcr_rating_stars_avg'
AND mt2.meta_key = 'post_views_count' )
AND wp_posts.post_type = 'book'
AND wp_posts.post_status = 'publish'

GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value DESC, mt1.meta_value DESC, mt2.meta_value  DESC

foreach( $pageposts as $postnum ){
  $i++;
  if($postnum->ID == $id){
     break;
  }
}

If there are other options, please post.

S
Sergey Gornostaev, 2020-09-21
@sergey-gornostaev

https://dev.mysql.com/doc/refman/8.0/en/window-fun...

R
Rsa97, 2020-09-21
@Rsa97

Where was it? If the record does not pass the condition, then it does not fall into the selection. Accordingly, in the selection, all records satisfy the condition and there are no other records before them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question