سؤال

I want to ask if this can be done by MySQL only and not by php code

i have a table that has

ID, CATID, Order

i know i can set the order by

SET @pos := 0; UPDATE products SET order = @pos :=@pos +1 ORDER BY order;

but how can i reset it ( starting from 0 on each catid ).

In php i can select each catid and run diferent sql each time.

Is there a solution of MySQL only?

( Also propose a title. I didnt know how to write it :P )

هل كانت مفيدة؟

المحلول

Introduce a new variable @cat. Compare with catid and reset the @pos on catid change

SET @pos := 0;
SET @cat:= 0;
UPDATE products p join 
  (
  select id, 
         @pos:=if(@cat<>catid,0,@pos+1) as new_order,
         @cat:=catid
  from products
  ORDER BY order
  ) p2 on p.id=p2.id
SET order = p2.new_order;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top