Mohan
Mohan

Reputation: 4829

Change enum column automatically

I have a column named status in a table which is of enum type and can have 2 values either 1 or 0. I want to write a query which will automatically check the current value of Enum and change to the other value.

For example, I have rows in table:

id   |  name   |  status
-----+---------+---------
  1  |  Abc    |    0
-----+---------+---------
  2  |  xyz    |    1

Now I want to write a mysql query where I pass the id of row to update and I will automatically check the current status and change it to the other. For example, if I pass id=1 it will automatically check the current value of status column and change it to 1. Similarly, if I pass id=2 it checks the status value of row 2 and changes it to 0.

Upvotes: 0

Views: 79

Answers (1)

Alma Do
Alma Do

Reputation: 37365

Here $id is your passed id. Note, that while bool operations (like status=!status) is "nifty", it's not good to work with ENUM-s such way.

UPDATE t SET status=IF(status='0', '1', '0') WHERE id=$id

also, good idea would be to change type to TINYINT if it's about storing 0 and 1 only (then status=!status will be good idea to use)

Upvotes: 1

Related Questions