使用if和else语句结果作为mysql中的变量

时间:2021-06-01 06:34:58

标签: mysql if-statement

大家好,

我需要帮助将 if 和 else 语句的结果用作以下 mysql 查询中的变量:

SELECT type, description, IF(type = 'Fixed Assets', 'true', 'false') AS description, IF(description = description, 'true', 'false') AS description2 FROM table_name;

我需要的是将“description”的结果用作另一列“description2”中的条件,这样我就不会一遍又一遍地使用相同的 IF 和 else 语句“description”。< /p>

description 的预期结果是 'true',而 description2 的预期结果也是 'true',因为 description 的值 = 'true'。

任何答案都会有很大帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

只需重复您的IF(type...)

select
    type,
    description,
    IF(type = 'Fixed Assets', 'true', 'false') AS description,
    IF(description = IF(type = 'Fixed Assets', 'true', 'false'), 'true', 'false') AS description2

您的另一个选择是子查询:

select type, description, is_fixed_assets, IF(description = is_fixed_assets, 'true', 'false') as description2
from (
    select type, description, IF(type = 'Fixed Assets', 'true', 'false') AS is_fixed_assets
    from table_name
) foo;