mysql - 如何使用 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;
解决方案
使用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;
推荐阅读
- javascript - 如何使用参数和#reference从http> https重定向网页
- ruby - Ruby 不允许我导入 BigDecimal 库
- javascript - 通过 php 创建 Javascript 数组
- dojo - 您可以在单独的文件(如角度)中创建组件以进行更模块化的设计吗
- xterm - URxvt 使用深色而不是浅色作为提示(xterm 使用)
- apache-spark - Spark Streaming 创建许多小文件
- javascript - 为什么在开发工具中检查时未定义 JS 中分配的变量?
- javascript - Convert javascript array into json array
- ios - 如何向 iOS UIWebView 添加导航?
- dump - 如何将特定进程转储到 RAM 文件