我正在努力获得指定记录的排名,我在这段代码中取得了一些成功:
SELECT `rank`
FROM
(
select @rownum:=@rownum+1 `rank`, p.*
from TableName p, (SELECT @rownum:=0) r
order by point DESC
) s
WHERE names = 'house'
此SQL查询有效,但如果我想根据city_id
和name
获取结果,我必须使用两个where
子句,然后代码不起作用。
我想仅为其城市获得house
等级。我怎么能这样做?
答案 0 :(得分:0)
我想只为其城市获得“房子”的等级
您可以通过引入另一个变量来跟踪城市来实现这一目标:
SELECT `rank`
FROM (select p.*,
(@rn := if(@c = city, @rn + 1,
if(@c := city, 1, 1)
)
) as rank
from TableName p CROSS JOIN
(SELECT @rn := 0, @c := -1) params
order by city_id, point DESC
) s
WHERE names = 'house' ;
如果你知道“house”只出现在数据中一次,你也可以使用原始查询进行调整:
SELECT `rank`
FROM (select p.*, (@rn := @rn + 1) as rank
from TableName p CROSS JOIN
(SELECT @rn := 0) params
where city_id = (select city_id from TableName t2 where t2.names = 'house')
order by point DESC
) s
WHERE names = 'house' ;