Mysql查看新字段值

时间:2018-09-21 06:21:34

标签: mysql view

如何根据同一视图中的另一个字段创建一个新字段?

例如:我有一个表car,其字段为car_name和car_type。

要根据其拥有的car_type(A,B,C或D)在视图“ price_class”中创建一个新字段

因此,如果car_type = A ,则price_class为> 100.000 。如果是                   B ,然后> 150.00 0                  对于 C D ,我想设置相同的值

CREATE VIEW `car_price` AS
SELECT 
    `car`.`car_name` AS `name`,
    `car`.`car_type` AS `car_type`
FROM
    `car`

提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式:

CREATE VIEW car_price AS
SELECT 
    car_name AS name,
    car_type AS car_type,
    CASE WHEN car_type = 'A' THEN '> 100.000'
         WHEN car_type = 'B' THEN '> 150.000'
         WHEN car_type IN ('C', 'D') THEN '> 300.000' END price_class
FROM car;

答案 1 :(得分:0)

根据使用案例的条件创建另一个字段

CREATE VIEW `car_price` AS
SELECT 

    `car`.`car_name` AS `name`,
    `car`.`car_type` AS `car_type`,
case when `car`.`car_type`='A' then '> 100.000'
when `car`.`car_type`='B' then '> 150.000'
when `car`.`car_type` in ('C','D') then '> 300.000' end as price_class 
FROM
    `car`