Home mysql Change the field value in order. SQL

Change the field value in order. SQL

Author

Date

Category

BD there is a table with ID 1 5 6 20 25
How to write a request that b to rename Iyidi in order, even at the end there should be 1 2 3 4 5, which would remain 1, the second (= 5) was 2, etc.?


Answer 1, Authority 100%

mysql:

update testn set id = (select @a: = @ a + 1)
 WHERE (SELECT @A: = 0) = 0
 Order by ID.

PostgreSQL (id must be unique):

update testn a set id = num
 from (
  SELECT ID, ROW_NUMBER () OVER (Order by id) Num
   From Testn.
 ) B.
 where b.id = a.id

Answer 2

This solution meets the SQL standard and should work on most dialects:

update tab u
SET U.ID = (
  SELECT NEWID FROM (
    SELECT ID, ROW_NUMBER () OVER (Order by ID) NewID From Tab) T
  Where t.id = u.id)

Answer 3

Usually, the “order number” is only needed in the view. For a relational base, it is unnatural.

On the example of php:

$ i = 1;
While ($ row = mysqli_fetch_assoc ($ result) {
 Echo ($ I ++). ' '. $ row [' id '].' '. $ Row [' Name ']. "& lt; br & gt; \ n";
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions