Begayim Muratalina
Begayim Muratalina

Reputation: 661

Replace the value of the variable by the value of the same variable but from different row

i need a help, i have a table in mysql with variable flight_id which looks like:

flight_id
1R10005
1M10000000000
1M10000000001
1M10000000002
1M10000000003
1M10000000004
1M10000000005
1M10000000006
1M10000000007
1R10006
1M10000000008
1M10000000009
1M10000000010
1M10000000011
1R10007
1M10000000012
1M10000000013
1M10000000014
etc....

i want to replace all flight_id which starts with '1M100' by the flight_id '1R1' i want to obtain table like this:

1R10005
1R10005
1R10005
1R10005
1R10005
1R10005
1R10005
1R10005
1R10005
1R10006
1R10006
1R10006
1R10006
1R10006
1R10007
1R10007
1R10007
1R10007

can someone help me with mysql query please :)

Upvotes: 0

Views: 82

Answers (3)

fthiella
fthiella

Reputation: 49079

You need an ID, or some other column to order your table. If you have an ID, you could use something like this:

UPDATE
  flights inner join (
    select f1.id, max(f2.id) as new_id
    from flights f1 left join flights f2
         on f1.flight_id like '1M100%'
            and f2.flight_id like '1R1%'
            and f1.id>f2.id
    group by f1.id) fmax
  on flights.id=fmax.id
  inner join flights fdesc
  on fmax.new_id=fdesc.id
SET
  flights.flight_id = fdesc.flight_id

Inner subquery returns, for every flight id, the new_id which is the id where to get the description from. This new_id is the maximum id < than current row, with the description like 1R1.

Upvotes: 1

Sashi Kant
Sashi Kant

Reputation: 13465

UPDATE myTable set flight_id=REPLACE(`flightId`, '1M100', '1R1') 
WHERE `flightId` LIKE '1M100%'

Upvotes: 2

Abubakkar
Abubakkar

Reputation: 15664

You can try this:

select CASE 
   WHEN `fklightId` like '1M100%' THEN REPLACE(`flightID`, '1M100', '1R1') END 
from your_tablename as flightId;

So now 1M10000000001 will be output as 1R100000001

And if you want to remove more zeros then increase number of zeros in the replace string

select CASE 
   WHEN `fklightId` like '1M100%' THEN REPLACE(`flightID`, '1M100000000', '1R1') END 
from your_tablename as flightId;

Will give 1M10000000001 as 1R101

Upvotes: 1

Related Questions