mysql - 顺序自连接 SQL
问题描述
我有一张如上所述的桌子。如何使用自联接按顺序获取输出,如下所示?
- 将烤箱预热到220摄氏度。
- 四个土豆去皮。
- 将土豆切成片。
- 将切好的土豆抹上油。
- 在预热好的烤箱里烤20分钟。
- 用盐和胡椒调味热切片。
select A.content
from recipe A
left join
(select
CASE WHEN previous_id IS NULL THEN 0 ELSE previous_id END previous_id,
CASE WHEN next_id IS NULL THEN 0 ELSE next_id END next_id
from recipe order by previous_id) B
on B.next_id = A.id;
我如何在这里使用previous_id?
用于重新创建表的 DDL 语句
create table recipes (id int, content varchar(50) , previous_id int, next_id int);
insert into recipes (id, content, previous_id, next_id) values (1, 'Preheat an oven to 220 degrees C.', NULL, 2);
insert into recipes (id, content, previous_id, next_id) values (2, 'Peel four potatoes.', 1, 4);
insert into recipes (id, content, previous_id, next_id) values (3, 'Toss sliced potatoes with oil.', 4, 6);
insert into recipes (id, content, previous_id, next_id) values (4, 'Cut potatoes into slices.', 2, 3);
insert into recipes (id, content, previous_id, next_id) values (5, 'Season the hot slices with salt and pepper.', 6, NULL);
insert into recipes (id, content, previous_id, next_id) values (6, 'Bake in the preheated oven for 20 minutes.', 3, 5);
解决方案
您不需要使用 JOIN。您只需要从表中选择所有数据(如果这只是表中的数据)和 ORDER BY previous_id。ORDER BY 总是将 NULL 值放在最前面(如果您不按 DESC 排序),然后您将按 previous_id 升序获得步骤。
SELECT * FROM recipes ORDER BY previous_id
看看这个演示。
推荐阅读
- c++ - unordered_map 的自定义哈希问题
- jquery - Mapael Map 如何使用 jquery 创建动态 json
- flutter - 从 Firestore 读取数据
- python - 为什么 peewee 在这种多对多关系中失败了?peewee.IntegrityError: UNIQUE 约束在直通表上失败
- python - 如何从命令行 odoo 11 卸载/更新模块
- hibernate - SQLite 数据库在执行 JAR 时没有响应
- python - 为什么 lemmatizer 在某些单词中不起作用?
- java - 如何处理appium中的阻塞页面?
- firebase - 仅使用 Firestore REST API 通过 DOC_ID 获取
- xamarin - Visual Studio 2019 for Mac:调试器无法连接到 iOS 设备