1

Similar to How to swap values of two rows in MySQL without violating unique constraint?, but not quite..

I have a table like this:

CREATE TABLE IF NOT EXISTS `links` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order` int(11) NOT NULL,
  `text` varchar(31) NOT NULL,
  `html_text` varchar(63) NOT NULL,
  `link` varchar(127) NOT NULL,
  `html_link` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `order` (`order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

It represents links in a navigation area of a website. E.g.: a link to the homepage, a link to the contact page, etc. I want to be able to change the order of these links, that's why I have the column order. The values of this column are unique, so I can sort by order.

Now I want to swap the positions of two links in this ordered list, so I want to swap the values of order. But unlike the other question, I do not know the value's of the order-fields, I only know the id values of the two rows I want to swap. I'd like to have only one query.

Can anybody help me with this, as I'm not very experienced with complex MySQL queries.

Community
  • 1
  • 1
Jochem Kuijpers
  • 1,770
  • 3
  • 17
  • 34

1 Answers1

4

There is no straight forward logic for this in a single query.

Conside you want to swap x,y

  1. You have to update first x with a different value z. (Some logic to arrive at a very unique value is required here).

  2. Then update y as x

  3. Then update z as y

RGV
  • 732
  • 3
  • 10