我有这个问题:
SELECT @ROWNUM := CASE WHEN @PREV_CAT_ID=T1.category_id THEN @ROWNUM+1 ELSE 1 END AS RANK,
@PREV_CAT_ID:=T1.category_id,
T1.*
FROM(d.category_id
FROM some_table d,
(SELECT @ROWNUM := 0)R
ORDER BY d.category_id
}T1
我想要为具有相同category_id的记录增加此RANK列。当category_id增加时,我希望等级重置为1并再次开始递增。
当我从TOAD执行查询时,这很有用,但是当我在我的Web应用程序中或从phpMyAdmin执行时,RANK总是1,无论我做什么。
有没有人知道,问题可能是什么?
谢谢!
答案 0 :(得分:3)
您应该每次都重置所有变量(@ROWNUM
和@PREV_CAT_ID
)。试试这个查询 -
SELECT
category_id, rank
FROM (
SELECT
category_id
, IF(@category_id = category_id, @num := @num + 1, @num := 1) AS rank
, @category_id := category_id
FROM some_table
CROSS JOIN (SELECT @num := 0, @category_id:= NULL) reset_all_vars
ORDER BY category_id
) t;