I am trying to insert data into a table in sorted order, for later fast retrieval. I am using an ordinal column to specify the order of the data. Like so:
SET @ctr = -1;
insert into search_data (trans_id, ordinal)
select trans_id, @ctr:=@ctr+1
from transactions
order by created;
created is a datetime field.
Doing the select without the insert has the rows coming back in the correct order, but the ctr variable does not increment correctly. E.g.:
+---+----------+--------------+---------------------+
| 1 | trans_id | @ctr:=@ctr+1 | created |
+---+----------+--------------+---------------------+
| 1 | 131379 | 232 | 2011-10-17 12:27:09 |
| 1 | 131377 | 231 | 2011-10-17 12:24:30 |
| 1 | 131311 | 230 | 2011-10-16 23:44:12 |
| 1 | 131305 | 229 | 2011-10-16 21:57:35 |
| 1 | 129948 | 46 | 2011-10-10 13:24:58 |
| 1 | 129947 | 45 | 2011-10-10 13:24:58 |
| 1 | 129946 | 44 | 2011-10-10 13:24:58 |
| 1 | 129945 | 43 | 2011-10-10 13:24:58 |
| 1 | 129944 | 42 | 2011-10-10 13:24:58 |
This technique has worked for me in MySQL 5.0, 4.x and 3.x. But it doesn’t work in 5.1.
It seems like the sort is being done after the variable is incremented, whereas previously the variable was incremented after the sort
Any thoughts?
Try subquery it:
asdfasdf