开发者

Updating a sequence of rows

开发者 https://www.devze.com 2023-03-21 13:23 出处:网络
I have a table sites and basically a travelling salesman problem. My boss wants to select a bunch of sites out of the list, then sort them manually into a visit order. I have looked for similar questi

I have a table sites and basically a travelling salesman problem. My boss wants to select a bunch of sites out of the list, then sort them manually into a visit order. I have looked for similar questions, but they were not targeted at MySQL, and those that were didn't provide a reasonable solution for my situation. I didn't do Computer Science at university, so hopefully this is bread-and-butter stuff for some of you out there.

I would like to do something like the following pseudo code:

UPDATE sites SET run_order=0 WHERE selected='false';
UPDATE sites SET run_order=AUTO_SEQUENCE(DESC FROM 6) WHERE site_id=SEQUENCE(23,17,9,44,2,14);

The latter of those would have the same effect as:

UPDATE sites SET run_order=6 WHERE site_id=23;
UPDATE sites SET run_order=5 WHERE site_id=17;
UPDATE sites SET run_order=4 WHERE site_id=9;
UPDATE sites SET run_order=3 WHERE site_id=44;
UPDATE sites SET run_order=2 WHERE site_id=2;
UPDATE sites SET run_order=1 WHERE site_id=14;

Since I am running this via PHP, I don't want to have to issue many individual queries, even though the number of sites my boss could visit in a day is of course limited by the internal combustion engine.

My SQL table looks like this:

+---------------+----------------------+------+-----+---------+----------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+----------------------+------+-----+---------+----------------+
| site_id       | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| ...           |                      |      |     |         |                |
| selected      | enum('false','true') | NO   |     | false   |                |
| run_order     | int(10) unsigned     | NO   |     | 0       |      开发者_运维问答          |
+---------------+----------------------+------+-----+---------+----------------+


I think this is the code you are looking for.

http://www.karlrixon.co.uk/articles/sql/update-multiple-rows-with-different-values-and-a-single-sql-query/

0

精彩评论

暂无评论...
验证码 换一张
取 消