开发者

mySql @ variables act differently from different clients

I have this query:

SELECT @ROWNUM := CASE 开发者_如何学GoWHEN @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 

I want this RANK column to increment for records with same category_id. When category_id increases, I want rank to reset to 1 and start incrementing again.

This works great when I execute my query from TOAD, but when inside my web application or when executed from phpMyAdmin the RANK is always 1, no matter what I do.

Does anyone have any idea, what the problem might be?

Thank You!


You should reset all variables (@ROWNUM and @PREV_CAT_ID) every time. Try this query -

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜