Chris Andrews
asked on
Mysql find and incrementally number matching rows?
I have a table, 'answers' and a field on that table 'q_id', and another field 'num' (nothing is in 'num' right now).
Is there a way to run a query that will find all rows with matching 'q_id' and number them by putting 1 or 2 or 3 or 4 or 5, ... in the 'num' field? That way I can identify them even though the q_id is the same.
If possible, can you put it together for me please?
Thank you, Chris
Is there a way to run a query that will find all rows with matching 'q_id' and number them by putting 1 or 2 or 3 or 4 or 5, ... in the 'num' field? That way I can identify them even though the q_id is the same.
If possible, can you put it together for me please?
Thank you, Chris
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
oh, hmmm, I do have a unique field, time_stamp, from the time the questions came in. I can even order by that.
Unfortunitly - I've got to be somewhere in about 20 minutes, so I can't try these solutions out right now. I will later this afternoon though :)
Chris
Unfortunitly - I've got to be somewhere in about 20 minutes, so I can't try these solutions out right now. I will later this afternoon though :)
Chris
OK - just make sure that the time_stamp column is immutable - once set, it stays set forever and that it is unique - no collisions whatsoever. Then if those two conditions are true, you can use it for the unique id
You should better add an autoincrement field and base your updates on this fields. It will be more efficient when you have more records in your table.
In oracle there you can select the unique rowid, but this option is not implemented in mysql.
In oracle there you can select the unique rowid, but this option is not implemented in mysql.
ASKER
Thank you xeonol, Ray and Fugas.
Xeonol's solution... I was a little hesitant on that one, looked - to - easy... but I ran it first since he posted the first solution and it ran right, with each matching row being numbered correctly, and on the first try!
Thank you!
Xeonol's solution... I was a little hesitant on that one, looked - to - easy... but I ran it first since he posted the first solution and it ran right, with each matching row being numbered correctly, and on the first try!
Thank you!
ASKER
And thank you Fugas and Ray for the extra tips on the use of 'num' and incrementing.
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
This is pidgin code, but hopefully the design pattern will be clear. It depends on something you did not mention - namely a UNIQUE field (perhaps an autoincrement key). If you don't already have one of these, use ALTER TABLE to add one.
Open in new window