简体   繁体   中英

add column to table and fill it under condition -mySQL

I have a simple table of hotels with rooms type and price for night. i need to add to this table a column called cheap/expensive and fill it with conditions: if the room price< 100 then fill in 'cheap' else fill in 'expensive'. how can i do it?

I started with:

ALTER TABLE rooms 
ADD `cheap/expensive` CHAR NOT NULL;

I would name it either cheap or expensive , not cheap/expensive . And the value of that should be (if column name is expensive ): 1 - for expensive, 0 - for cheap. With integer values it's faster and takes less storage.

ALTER TABLE rooms 
ADD `expensive` INT(1) NOT NULL DEFAULT 0;

Then you should have conditions before each insert to table with proper language you use, Java, PHP, Python etc.

Other way is to use TRIGGERS , but I wouldn't recommend that solution if you use backend language to verify your data.

Example trigger for this column when inserting new rows:

CREATE TRIGGER expensivecheck BEFORE INSERT ON rooms FOR EACH ROW IF NEW.price >= 100 THEN SET NEW.expensive = 1; END IF;

Since this is derived and subjective information, it's more likely something you would do in your code or query than directly as data in your database. For example, if you later update a price, you'd have to be cognizant of whether to update whether it's cheap or expensive. Or if you later decide to change the dividing line (eg to $110 or as a function of average household income), or that you need more fine-grained price categories (eg Cheap|Moderate|Expensive), it's easier and safer to change your algorithm rather than change your data.

Example query:

SELECT *, IF (price < 100, "Cheap", "Expensive") as price_category FROM room;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM