Reputation: 193
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?
Upvotes: 4
Views: 165
Reputation: 8647
I would modify the second query to only update rows that WON'T be updated in the third, like so:
SELECT @i:=0;
UPDATE imagedata SET imagedata.rank = 0 WHERE imagedata.kategorieID <> 1;
UPDATE imagedata SET imagedata.rank = (SELECT @i:=@i+1) WHERE imagedata.kategorieID = 1;
EDIT: Per Lamak's comment, if the kategorieID
could be NULL
you'll want to do this instead:
SELECT @i:=0;
UPDATE imagedata SET imagedata.rank = 0 WHERE imagedata.kategorieID <> 1 OR imagedata.kategorieID IS NULL;
UPDATE imagedata SET imagedata.rank = (SELECT @i:=@i+1) WHERE imagedata.kategorieID = 1;
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 that WHERE
first. Perhaps you should test the performance of this first to see if it is truly faster.
Upvotes: 1