【问题标题】:Sequential self join SQL顺序自连接 SQL
【发布时间】:2025-12-28 16:55:07
【问题描述】:

我有一张如上所述的桌子。如何使用自连接来按顺序获取输出,如下所示?

  1. 将烤箱预热至 220 摄氏度。
  2. 给四个土豆削皮。
  3. 将土豆切成片。
  4. 将土豆片倒入油中。
  5. 在预热好的烤箱中烘烤 20 分钟。
  6. 用盐和胡椒调味热切片。
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);

【问题讨论】:

标签: mysql sql


【解决方案1】:

您不需要使用 JOIN。您只需要从表中选择所有数据(如果这只是表中的数据)和 ORDER BY previous_id。 ORDER BY 总是把 NULL 值放在最前面(如果你不按 DESC 排序的话),然后你会得到按 previous_id 升序排列的步骤。

SELECT * FROM recipes ORDER BY previous_id

看看这个demo.

【讨论】:

  • 按 previous_id 排序会得到“在预热的烤箱中烘烤 20 分钟”。作为第四行,这不是我们预期的答案,因为“用油拌土豆片”。是我们在第四行的预期答案。
  • 您需要为“在预热的烤箱中烘烤 20 分钟”编辑 previous_id。到 4. 将列 previous_id 重新排序为:NULL, 1, 3, 2, 5, 4