2

I am trying to compute the ranks for a MySQL table, ranking by a table colum that also contains NULL value. I found the snippet from this questions's answer, and adapted it to my use case, but it doesn't work - it seems that the @rownum := @rownum + 1 as rank is computer prior to ordering by order by.

My question is: why does this happen? Is doing the variable increment before the order by standard MySQL behavior? does it have anything to do with the NULLs (should't they just get ordered last and not affect anything else?).

Now, I have already solved my rank computing problem with a subquery in the SELECT clause, but I was hoping that this method with the variable would be more efficient because there is no subquery involved, and I also want to get a better understanding of how variables in queries work.


This is an example query (note: global_average_rating_overall also contains NULLs - could this be the cause for weird behavior?):

set @rownum := 0;
select
    ID,
    post_title,
    m.meta_value as global_average_rating_overall,
    @rownum := @rownum + 1 as rank
from
    wp_posts p
    left join wp_postmeta m on m.post_id = p.ID and m.meta_key = 'global_average_rating_overall'
where
    p.post_status = 'publish'
order by global_average_rating_overall desc;

The result is along the lines of:

ID  global_average_rating_overall  rank
--+------------------------------+-----
3   4                              14
9   3.9                            22
7   3.75                           11
...                                 1
...                                 2
...                                 3

(note the last ranks that don't match the ranking by global_average_rating_overall)

4

1 回答 1

0

在查询执行期间读取和写入同一个变量是未定义的。如果排序是由索引执行的,则分配可能与在临时表中执行排序不同。

于 2013-05-17T18:11:32.503 回答