【发布时间】:2025-12-28 16:55:07
【问题描述】:
我有一张如上所述的桌子。如何使用自连接来按顺序获取输出,如下所示?
- 将烤箱预热至 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);
【问题讨论】:
-
这是一个很好的起点,但不能完全回答我的问题。
-
@DaleK 这些解决方案都不是 MySQL,它们都涉及递归,直到版本 8 才在 MySQL 中提供