首页 > 解决方案 > 在mysql中使用if和else语句结果作为变量

问题描述

今天是个好日子,

在下面的 mysql 查询中使用 if 和 else 语句的结果作为变量时,我需要帮助:

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

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

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

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

标签: mysqlif-statement

解决方案


只需重复您的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;

推荐阅读