I have two tables in my database, foo
and bar
. Multiple foo
s have one bar
, and contain a second column that controls the ordering of foo
s with the same bar
. The values used for ordering should be unique, so the table has a unique constraint:
CREATE TABLE bar (
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE foo (
id INT NOT NULL AUTO_INCREMENT,
bar INT,
`order` INT,
PRIMARY KEY (id),
FOREIGN KEY (bar) REFERENCES bar (id),
UNIQUE KEY (bar, order)
);
What is the most efficient way to update the ordering of the foo
s for one bar? For example, if I have this data:
id | bar | order
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 1 | 4
And want to reorder them (1, 2, 4, 3), I now have the following queries:
UPDATE foo SET `order` = NULL WHERE id IN (3, 4);
UPDATE foo SET `order` = 3 WHERE id = 4;
UPDATE foo SET `order` = 4 WHERE id = 3;
The first query is necessary to prevent an integrity error for the other updates. Can this be improved?