MySQL排名计算失败,变量始终为null

时间:2014-01-12 15:32:18

标签: mysql sql

我想根据同一行中的rating列的值维护MySQL表中每行的存储排名索引。我找到了解决方案herehere,但它不起作用。

SELECT * FROM `MyTable` T
JOIN
(
    SELECT `id`, @rownum=@rownum+1 AS `rank_calculated`
    FROM `MyTable`, (SELECT @rownum=0) AS `inline_trick`
    ORDER BY `rating`
) R
ON R.`id` = T.`id`

这将选择MyTable中的所有行,但rank_calculated列始终为null。谁能告诉我为什么?

mysql Ver 14.14 Distrib 5.5.34,debian-linux-gnu(i686)使用readline 6.2

1 个答案:

答案 0 :(得分:1)

尝试使用:=

SELECT *
FROM `MyTable` T JOIN
     (SELECT `id`, @rownum:=@rownum+1 AS `rank_calculated`
      FROM `MyTable`, (SELECT @rownum:=0) AS `inline_trick`
      ORDER BY `rating`
    ) R
    ON R.`id` = T.`id`;

编辑:

为了清楚起见,在select语句中=引用了布尔比较,而不是赋值。您需要:=来完成作业。您可以阅读更多here