Trying to basically re-count the primary column, meaning updating from the first to the last, incrementing the value with each row. First I am selecting,
select
`someid`,
`time`
from
`table`
ORDER BY
`time` ASC
fetching the result,
$data = new SplFixedArray($query->num_rows);
$data = $query->fetch_all();
and updating the table.
for($i=1; $i<count($data); $i++){
print_r("UPDATING | New someid: " . $i . " WHERE old someid: " . $data[$i][0] . " AND time = " . $data[$i][1] . "<br />");
$query = $mysqli->query("UPDATE `table` SET `someid` = '" . $i . "' WHERE `time` = '" . $data[$i][1] . "' AND `someid` = '".$data[$i][0]."'");
}
What confuses me is, that the first few entries aren't sorted correctly. It's like
someid | time
--------------
0 | 0
2 | 1
1 | 2
7 | 3
11 | 4
6 | 5
It's because of duplicates. After the 15ish rows in "someid" there is a gap and it jumps to 60. So after that there are no more duplicate someids. But how can I handle the first few rows? If I want to update someid to 2 but 2 is already existent?
Any way to handle that without using too many querys?
Edit:
Maybe it's unclear to some. Basically I am trying to refresh the int-values from a primary column. So basically I am counting them and enter their appropriate number into someid, sorted by sometime. Sometime is datetime. So the earliest "sometime" would get "someid" = 1.
At the moment, someid has gaps. 1..2..3..4..5..6..7..15..16..17..18..30..31..32 Updating, like I am doing now, doesn't work until I reach a gap. Because I am trying to write a duplicate value. Updating the first someid to 1, which might be of value 11, does not work because someid 1 is already existent somewhere.
I would update someid 15 to 8, because it's the next number. This works because 8 to 14 are missing, and I am not duplicating a value.
One solution might be to create another loop and first update every someid to some made up number, maybe start counting from row->count, incrementing for every row. After that, I can update them as I'd do normally. But isn't there a better solution?
// UPDATE:
This:
SET @count = 0;
UPDATE `table` SET `table`.`someid` = @count:= @count+ 1;
"Resets" the IDs, but it doesnt sort them by time.
Trying this:
SET @count = 0;
UPDATE `table` SET `table`.`someid` = @count:= @count+ 1;
ORDER BY `time` DESC;
Gives me the following error:
Duplicate entry '1' for key 'PRIMARY'