首页 > 解决方案 > 如何使用 IF 条件将旧 SQL 转换为最新 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.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 中运行它时,这个查询也给了我错误 - 雪花。这是我第一次看到这种类型的 IF 条件。以及重写查询的解释和帮助。数据是一个简单的父子关系表。

我想做的是:

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;

标签: mysqlsql

解决方案


使用case表达式:

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;

推荐阅读