【问题标题】:How to use IF() [Control Flow Function] case in the Select statement?如何在 Select 语句中使用 IF() [控制流函数] case?
【发布时间】:2012-09-04 15:25:23
【问题描述】:

我需要从单列 price 中创建两列,具体取决于它是 used/secondhand 还是新列。旧的由usedformat 列中的某处表示。一种是“不含税价格”,另一种是含税price。我希望下面的代码(没有错误但根据我的要求出现故障)更好地解释它。

format ='%used%' 或 format='%secondhand%' 然后 CAST(price AS UNSIGNED INTEGER) else CAST(price AS UNSIGNED INTEGER)*0.8 end as 'Pris ex Tax', CAST(price AS UNSIGNED INTEGER) as Price

这里基本上我需要为新产品显示一个价格*0.8 的列,而对于旧产品只显示price。 数据库中的format 包含旧文章的信息,如used/secondhand,但没有新的。

我关注了this link 以及stackoverflow中的一些相关问题 但不足以让我理解。 我试图把输出放在这里,但发现很难做到。如果您认为需要解决它,我会这样做。

【问题讨论】:

    标签: mysql sql select if-statement


    【解决方案1】:

    This is a great link that teaches Inline IF and CASE statement in MySQL.

    代码sn-p:

    IF Statement

    SELECT IF(score > 100, 100, score) AS score
    FROM exam_results
    

    CASE Statement

    SELECT CASE num_heads
    WHEN 0 THEN 'Zombie'
    WHEN 1 THEN 'Human'
    ELSE 'Alien'
    END AS race
    FROM user
    

    【讨论】:

    • John Woo 感谢您的快速回复,我可以理解这段代码,但是在使用if 比较string 时,我很困惑。考虑我在问题中的代码中位于其他字符串中间的字符串比较是否有帮助?
    • @tough 可以试试这个 sn-p CASE WHEN format LIKE '%used%' OR format LIKE '%secondhand%' 使用 LIKE 而不是 =等号
    • @tough 还请注意,当转换为整数时,它只能是 signedunsigned ex CAST(price AS UNSIGNED)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多