ALTER TABLE many_to_many ADD order_column INT;
CREATE TEMPORARY TABLE tmp_many_to_many AS (
SELECT many_to_many.id,
many_to_many.type_id,
(
CASE many_to_many.type_id
WHEN @type_id THEN @cur_row := @cur_row + 1
ELSE @cur_row := 1 AND @type_id := many_to_many.type_id
END
) AS `order_column`
FROM many_to_many,
(SELECT @cur_row := 0, @type_id := 0) var_table
ORDER BY many_to_many.type_id, many_to_many.id
);
UPDATE many_to_many, tmp_many_to_many
SET many_to_many.order_column = tmp_many_to_many.order_column
WHERE many_to_many.id = tmp_many_to_many.id;