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