I have this table :
id ref data
1 111 data1
2 111 data2
3 111 data3
4 111 data4
5 222 data1
6 222 data2
7
MySQL doesn't support analytics (IE: ROW_NUMBER), which are what you'd use for the output you're after. Use:
SELECT x.id, x.ref, x.data, x.rank AS `order`
FROM (SELECT t.id, t.ref, t.data
CASE
WHEN @ref = t.ref THEN @rownum := @rownum + 1
ELSE @rownum := 1
END AS rank,
@ref := t.ref
FROM YOUR_TABLE t
JOIN (SELECT @rownum := NULL, @ref := -1) r
ORDER BY t.id, t.ref, t.data) x
Usually, this would require separate statements to declare the @rownum and @ref variables but MySQL lets you get away with it if they are defined like you see in the example.
The CASE statement resets the @rownum value to one if the ref
values don't match. Otherwise, @rownum increments by one. The column the incrementing @rownum value is associated with is determined by the ORDER BY
clause.
I believe if you create a primary key that looks like (ref, order) where order is an auto_increment, you can have have the database create this for you automatically.
http://mysqldump.azundris.com/archives/5-AUTO_INCREMENT-Trivia.html