简体   繁体   English

将列添加到表并在 -mySQL 条件下填充

[英]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'.我需要在此表中添加一个名为“ cheap/expensive ”的列并填写条件:如果房价< 100,则填写“便宜”,否则填写“昂贵”。 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 .我会把它命名为cheapexpensive ,而不是cheap/expensive And the value of that should be (if column name is expensive ): 1 - for expensive, 0 - for cheap.它的值应该是(如果列名很expensive ):1 - 昂贵,0 - 便宜。 With integer values it's faster and takes less storage.使用 integer 值,它更快,占用更少的存储空间。

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.然后你应该在每次插入表格之前使用你使用的正确语言,Java,PHP,Python 等有条件。

Other way is to use TRIGGERS , but I wouldn't recommend that solution if you use backend language to verify your data.其他方法是使用TRIGGERS ,但如果您使用后端语言来验证您的数据,我不会推荐该解决方案。

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.或者,如果您后来决定更改分界线(例如更改为 110 美元或作为平均家庭收入的 function),或者您需要更细粒度的价格类别(例如便宜|中等|昂贵),更改您的算法而不是更改您的数据。

Example query:示例查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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