Mysql 如何使用IF条件将较旧的SQL转换为最新的SQL?

Mysql 如何使用IF条件将较旧的SQL转换为最新的SQL?,mysql,sql,Mysql,Sql,我试图理解并重新编写一个查询。SQL风格是我无法理解的。以下是查询: SELECT wc1.id AS category_id, wc1.name AS category_name, if(wc3.parent_id is not null, wc4.name, if(wc2.parent_id is not null, wc3.name, if(wc1.parent_id is not null, wc2.name, wc1

我试图理解并重新编写一个查询。SQL风格是我无法理解的。以下是查询:

SELECT wc1.id AS category_id, wc1.name AS category_name,
        if(wc3.parent_id is not null, wc4.name, 
           if(wc2.parent_id is not null, wc3.name, 
              if(wc1.parent_id is not null, wc2.name, wc1.name))) as ultimate_parent
    FROM CATEGORIES wc1
    LEFT JOIN categories wc2 ON wc1.parent_id = wc2.id
    LEFT JOIN categories wc3 ON wc2.parent_id = wc3.id
    LEFT JOIN categories wc4 ON wc3.parent_id = wc4.id;
我无法理解查询的IF,IF,IF部分。当我在Dbeaver-snowflake中运行这个查询时,它也会给我带来错误。 这是我第一次看到这种情况。以及重新编写查询时的解释和帮助。数据是一个简单的父子关系表

我想做的是:

SELECT wc1.id AS category_id, wc1.name AS category_name,
        if wc3.parent_id is not null then wc4.name, 
           if wc2.parent_id is not null then wc3.name, 
              else wc1.parent_id is not null Then wc2.name, wc1.name as ultimate_parent -- I am having issues with splitting the last if clause
    FROM CATEGORIES wc1
    LEFT JOIN categories wc2 ON wc1.parent_id = wc2.id
    LEFT JOIN categories wc3 ON wc2.parent_id = wc3.id
    LEFT JOIN categories wc4 ON wc3.parent_id = wc4.id;

使用
大小写
表达式:

SELECT wc1.id AS category_id, wc1.name AS category_name,
       (case when wc3.parent_id is not null then wc4.name 
             when wc2.parent_id is not null then wc3.name 
             when wc1.parent_id is not null then wc2.name
             else wc1.name
        end) as ultimate_parent
FROM CATEGORIES wc1 LEFT JOIN
     categories wc2 ON wc1.parent_id = wc2.id LEFT JOIN
     categories wc3 ON wc2.parent_id = wc3.id LEFT JOIN
     categories wc4 ON wc3.parent_id = wc4.id;

只有MySQL支持
IF
(以及
CASE
)。大多数其他数据库对条件逻辑表达式使用ANSI
CASE
语句。您从第一个查询中得到了什么错误?第二个查询的语法无效,因为if-then的形式在sql查询中无效。