English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Suppose I have a table with the field 'sequence' , there are 2 records with sequence 2 and 3. I wanna swap these, ie the record with sequence 2 should get updated as 3 and vice versa. Is it possible to do it in a single query?

2007-01-15 16:40:13 · 4 answers · asked by WhizGirL 4 in Computers & Internet Programming & Design

Btw.. there will be more than one record with sequence 2 and 3 ..I wanna update that as well

2007-01-15 16:52:05 · update #1

4 answers

No you would be trying to mix a select query and an update query into one. This doesn't (to my knowlege) work with MySql.

Your best and safest bet is to do your select query and use PHP to swap the values and store the updated records with an update query.

2007-01-15 16:46:20 · answer #1 · answered by afreshpath_admin 6 · 0 1

No don't think it is possible in a single query, and I don't think it's even possible in 2. It is possible in 3.

The problem lies as follows: when u update the 2's into 3's (or the other way around) all ur seq 2 AND 3 are gonna be the same number for a fraction of a second (even in a single query, it is most likely still being executed in sequence). Because of that, all ur 2's and 3's are going to be converted to the same number.

To avoid this, do a standard swap
temp = a
a = b
b = temp

as far as SQL goes, do an UPDATE instead of an assign (=).
so it would look as follows
- update seq 2's to -1 (or any other unused sequence #)
- update seq 3's into seq 2's
- update seq -1 to seq 3's

hope this helps

P.S. selecting into PHP and swapping it there will probably take more time because u're doing 2 select and tons of updates (one per record), just think about it.

2007-01-15 17:18:08 · answer #2 · answered by rice kid 4 · 0 0

Yes.

2007-01-15 16:47:25 · answer #3 · answered by Jorge's Wife 4 · 0 1

the answer to your question is yes you can achieve this using nested sql

2007-01-15 18:47:18 · answer #4 · answered by Adeel I 3 · 0 0

fedest.com, questions and answers