作为子查询运行时数据不正确

时间:2014-05-29 22:56:39

标签: sql mysqli

我有一个查询,它从与用户表连接的表中获取有关给定媒体的数据 :

SELECT media.id, media.user_id,@rownum := @rownum + 1 AS position 
INNER JOIN users
ON media.user_id = users.id
FROM media_table 
ORDER BY media.distance ASC, media.media_likes_count DESC, media.media_views_count Desc;

此查询生成一个漂亮的表,如下所示:

media_id, user_id, position
39199   , 3949   , 1
39299   , 3149  , 2
39359   , 3944   , 3
39369   , 3349   , 4
39379   , 3149   , 5
39389   , 3449   , 6

从这个派生表中,我想得到media_id = 39389的位置。

但是,如果我在子查询中包含该查询,请执行以下操作:

Select position from (SELECT media.id, media.user_id,@rownum := @rownum + 1 AS position from 
INNER JOIN users
ON media.user_id = users.id
FROM media_table 
ORDER BY media.distance ASC, media.media_likes_count DESC, media.media_views_count Desc;)
where media_id = 39389

然后列'shuffle'和39389不再有位置6。

1 个答案:

答案 0 :(得分:2)

如果您的查询中存在错误,假设这些错误只是错别字,那么您的问题可能就是初始化user defined variable。这个浓缩版本适用于我:

select postition
from (
  select yourresults.*, @rn:=@rn+1 postition
  from yourresults 
    join (select @rn:= 0) t
  order by media_id
  ) t
where media_id = 39389

虽然这不起作用:

select postition
from (
  select yourresults.*, @rn:=@rn+1 postition
  from yourresults 
  order by media_id
  ) t
where media_id = 39389