I do 3 queries to reorder the rows of my table
SELECT @i:=0;
UPDATE imagedata SET imagedata.rank = 0;
UPDATE imagedata SET imagedata.rank = (SELECT @i:=@i+1) WHERE imagedata.kategorieID = 1;
which I execute from top to bottom.
Question: Is ther a shorter way to do this?
thx for all the feedback..
but i have a differnet Idear now:
Somehow I have to “connect” the “kategorieID” with the “id(Primary key)” collumn
Therefore I need to store both information into the “rank” collumn in the format like:
cxxx
c=Category Number(0 to 4)
xxx = id (1 to …n)..unique!
exampl.: output:
rank
+------+
+ 1001 +
+ 1002 +
+ 1003 +
+ ... +
+ 1018 +
+ ... +
+ 2001 +
+ 2002 +
+ 1019 +
+ 1020 +
so far I did it like:
UPDATE imagedata SET imagedata.rank = (SELECT CONCAT(kategorieID,"",LPAD(id,3,'0')) ) WHERE id=88;
once that “rank” is filled with data it gives me the abillity to swap 2 id’s.
Therefore I have to:
1) get “rank” collumn of id_1 and id_2
2) get the substring (‘xxx’) of that string exampl: (“004” .. “012”)
3) exchange substrings of id_1 “rank” and id_2 “rank”
SELECT @ix1:=SUBSTRING(rank, -3) FROM imagedata WHERE id=88;
SELECT @ix2:=SUBSTRING(rank, -3) FROM imagedata WHERE id=83;
..I know how to get it but dont know how to exchange it?
I would modify the second query to only update rows that WON’T be updated in the third, like so:
EDIT: Per Lamak’s comment, if the
kategorieIDcould beNULLyou’ll want to do this instead:Also, it’s possible that this solution may be slower than yours, especially if there isn’t an index on
kategorieID. I say this because even though you are updating less rows, it now has to filter on thatWHEREfirst. Perhaps you should test the performance of this first to see if it is truly faster.