我正在为正在工作的wordpress主题构建队列插件。我正在使用单向链接列表来完成此操作。每行在数据库中都有一个“ previous_item_id”列,该列指向应在此之前打印的行!需要ODRDER BY向导,大声笑,谢谢您
当前数据库表:
ID EMAIL PREVIOUS_ITEM_ID
1 test@gmail.com NULL
2 test2@gmail.com 1
3 test3@gmail.com 4
4 test4@gmail.com 2
5 test5@gmail.com 3
我该如何编写一个使用Order By来按previous_item_id
抓取下一行的SQL语句,如下所示:
previous_item_id
(以第一个为准)基本上,previous_item_id
的初始行为NULL,然后通过ID递归地获取下一行。
订单的输出应打印: 应该打印什么:
test@gmail.com
test2@gmail.com
test4@gmail.com
test3@gmail.com
test5@gmail.com
答案 0 :(得分:0)
使用case expression
,例如:
order by case when PREVIOUS_ITEM_ID IS NULL then 0 else PREVIOUS_ITEM_ID end
MAIL
test@gmail.com
test2@gmail.com
test4@gmail.com
test5@gmail.com
test3@gmail.com
答案 1 :(得分:0)
您可以使用相关子查询获取上一个商品ID:
select t.*,
(select t2.id
from t t2
where t2.id < t.id
order by t2.id desc
limit 1
) as prev_id
from t;
答案 2 :(得分:0)
SELECT yourtable.email
FROM yourtable
ORDER BY previous_item_id
幸运的是,您不需要递归,因为所有记录都是相关的。如果还有其他键,只需将它们添加到where。
答案 3 :(得分:0)
无法完成。基础数据结构是任意链接列表。 ORDER BY需要一个表达式来对数据结构中的项目进行排序。在任意链接列表中,此表达式不存在。
请注意,部分问题在逻辑上是不正确的。
the first item should have no previous_item_id(Which makes it first)
the second item should have 1 as the previous_item_id
the third item should have 2 as the previous item_id
the fourth item should have 3 as the previous_item_id
在任意链接列表中,键不一定是连续的升序。