我有一个MySQL查询,我想在其中添加rank
列。
SELECT AM.* , count(ALM.id) as likes FROM admin_models as AM
left join admin_liked_models as ALM on AM.id = ALM.admin_model_id
group by AM.id
admin_models
和admin_liked_models
有一对多关系。
最高likes
应为1级。
有人能指出我怎么做吗?谢谢!
答案 0 :(得分:1)
不幸的是,MySQL并不支持Row_Number()
或其他分析功能。以下是产生相同结果的一种方法:
SELECT *,
@rn:=@rn+1 rn
FROM (
SELECT AM.* , count(ALM.id) as likes
FROM admin_models as AM
LEFT JOIN admin_liked_models as ALM ON AM.id = ALM.admin_model_id
GROUP BY AM.id
) t, (SELECT @rn:=0) t2
ORDER BY likes DESC
您可能不需要子查询,但我只是展示了分离。
答案 1 :(得分:0)
这仅适用于使用ORDER BY时,是否无法根据喜欢列数制作排名列?
看起来你不是在寻找rank
。如果你不想使用ORDER
并希望将等级用作某个等级,你可以尝试这样的事情:
SELECT AM.* , count(ALM.id) as likes,
((SELECT max(maxval) from
(SELECT count(ALM.id) as maxval FROM admin_models as AM
left join admin_liked_models as ALM on AM.id = ALM.admin_model_id
group by AM.id) as subq) - count(ALM.id) + 1) as rank
FROM admin_models as AM
left join admin_liked_models as ALM on AM.id = ALM.admin_model_id
group by AM.id
请注意,在这种情况下,成绩不会是连续的,而且几个型号的成绩相同。