Fetching linked list in MySQL database

后端 未结 3 1797
孤街浪徒
孤街浪徒 2020-11-29 08:06

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 t

3条回答
  •  悲哀的现实
    2020-11-29 08:22

    This is less a solution and more of a workaround but, for a linear list (rather than the tree Bill Karwin mentioned), it might be more efficient to use a sort column on your list. For example:

    TABLE `schema`.`my_table` (
        `id` INT NOT NULL PRIMARY KEY,
        `order` INT,
        data ..,
        INDEX `ix_order` (`sort_order` ASC)
    );
    

    Then:

    SELECT * FROM `schema`.`my_table` ORDER BY `order`;
    

    This has the disadvantage of slower inserts (you have to reposition all sorted elements past the insertion point) but should be fast for retrieval because the order column is indexed.

提交回复
热议问题