如果那么Else Mysql

时间:2014-10-04 22:15:52

标签: mysql database

在一个表中处理从两个表中拉出来的视图但是我需要选择一个字段或另一个字段,具体取决于第三个字段...就是那个有我存根的if。

 Create view as 
      select
           pens.PartNo,
           pens.Title,
           ranges.weight 
           if(pens.SpeacialOffer = 1 then pens.offer as Price else pens.Price)
      from
           pens, ranges 
      where   
           pens.penrange = ranges.id;

如果特价商品被愚弄,那么该视图需要提供优惠,否则需要提取价格。

3 个答案:

答案 0 :(得分:3)

您需要的是CASE operator

CASE
     WHEN condition
     THEN value_a
     ELSE value_b
END

所以在你的情况下:

CASE
     WHEN pens.SpeacialOffer = 1
     THEN pens.offer
     ELSE pens.price
END

这将替换SELECT语句中的整个列定义,因此整个视图变为:

Create View as 
    Select 
        pens.PartNo,
        pens.Title,
        ranges.weight,
        Case
            When pens.SpeacialOffer = 1
            Then pens.offer
            Else pens.price
        End as Price
    From 
        pens, ranges 
    Where
        pens.penrange = ranges.id;

答案 1 :(得分:0)

使用CASE,也将查询转换为显式连接而不是隐式连接

  select pens.PartNo,  
       pens.Title,
       ranges.weight,      
       (Case when  
        pens.SpeacialOffer = 1 then   
        pens.offer else pens.Price 
        end ) as Price 
      FROM pens, 
      JOIn ranges 
      ON pens.penrange = ranges.id;

答案 2 :(得分:0)

这是一种方式:

Create view as select
  pens.PartNo,
  pens.Title,
  ranges.weight,
  (pens.SpeacialOffer * pens.offer + (1 - pens.SpeacialOffer) * pens.price) as Price
from
  pens,
  ranges
where
  pens.penrange = ranges.id;