mysql 链表类型,在MySQL数据库中获取链表

针对一个具有next_id字段表示链式链接的MySQL数据库表,如何按顺序获取数据。虽然MySQL不直接支持递归查询,但可以通过多次LEFT JOIN实现。例如,通过LEFT JOIN最多到第10层来获取数据,虽然效率较低,但能获取所需结果。如果需要限制返回的深度,可以在客户端进行处理。
摘要由CSDN通过智能技术生成

I have a MySQL database table with this structure:

table

id INT NOT NULL PRIMARY KEY

data ..

next_id INT NULL

I need to fetch the data in order of the linked list. For example, given this data:

id | next_id

----+---------

1 | 2

2 | 4

3 | 9

4 | 3

9 | NULL

I need to fetch the rows for id=1, 2, 4, 3, 9, in that order. How can I do this with a database query? (I can do it on the client end. I am curious if this can be done on the database side. Thus, saying it's impossible is okay (given enough proof)).

It would be nice to have a termination point as well (e.g. stop after 10 fetches, or when some condition on the row turns true) but this is not a requirement (can be done on client side). I (hope I) do not need to check for circular references.

解决方案

Some brands of database (e.g. Oracle, Microsoft SQL Server) support extra SQL syntax to run "recursive queries" but MySQL does not support any such solution.

The problem you are describing is the same as representing a tree structure in a SQL database. You just have a long, skinny tree.

There are several solutions for storing and fetching this kind of data structure from an RDBMS. See some of the following questions:

Since you mention that you'd like to limit the "depth" returned by the query, you can achieve this while querying the list this way:

SELECT * FROM mytable t1

LEFT JOIN mytable t2 ON (t1.next_id = t2.id)

LEFT JOIN mytable t3 ON (t2.next_id = t3.id)

LEFT JOIN mytable t4 ON (t3.next_id = t4.id)

LEFT JOIN mytable t5 ON (t4.next_id = t5.id)

LEFT JOIN mytable t6 ON (t5.next_id = t6.id)

LEFT JOIN mytable t7 ON (t6.next_id = t7.id)

LEFT JOIN mytable t8 ON (t7.next_id = t8.id)

LEFT JOIN mytable t9 ON (t8.next_id = t9.id)

LEFT JOIN mytable t10 ON (t9.next_id = t10.id);

It'll perform like molasses, and the result will come back all on one row (per linked list), but you'll get the result.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值