5

I have a table structure

kinda like this

id  |   title | next 
1   |  test   | 5
2   |  test   | 0
3   |  test   | 0
4   |  test   | 0
5   |  test   | 3

Now, as you see 1 points to next item 5 and 5 points to next item 3 and 3 denotes the end

I need a query, from which I can get 1, 5, 3 serially in one column and their title also

like

result | title
--------------
1      |  test
5      |  test
3      |  test
--------

please help. I dont even know how to get started at such query.

mrN
  • 3,734
  • 15
  • 58
  • 82

3 Answers3

1

What you need is a tree query - check Is it possible to query a tree structure table in MySQL in a single query, to any depth?

Community
  • 1
  • 1
Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
  • I saw your link, but I am lost. I dont know how to implement it, in my case. May be a small example. – mrN Apr 05 '11 at 12:40
1

What you want to do here is join the table on itself.

SELECT * FROM `table` AS `child` 
JOIN `table` AS `parent` 
ON `parent`.`next` = `child`.`id`

You need to give both copies of the table their own alias (here: parent and child) because otherwise you will run into uniqueness troubles.

Kokos
  • 9,051
  • 5
  • 27
  • 44
0

One way would be to create a loop that repeats a simple query.. I could post an example here. Are you using PHP?

pragmatic
  • 121
  • 3