Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have this simple table with 2 columns "number" and "previous number"defined with this values:
number | previous number
281 | 0
280 | 281
279 | 280
278 | 279
277 | 278
276 | 277
275 | 276
274 | 275
273 | 274
272 | 273

and the following select
select 
    tmp.op_nr,
    @op_nr := tmp.previous_op_nr,
    @depth:=@depth+1
from 
     (select @op_nr=280, @depth:=0 ) as vars,
    dwh.temporary_table tmp
   
where tmp.op_nr=@op_nr and 
    @depth<10;


and for this query it should return
VB
281 | 0
280 | 281
279 | 280

if i change the depth to 2 and @op_nr to 275
it should return something like
VB
277 | 278
276 | 277
275 | 276


but i am missing something in the select statement and doesn't work like this.
what modification should i make?
Posted
Comments
Richard C Bishop 12-Mar-13 12:23pm    
What results are you getting if not the desired results?
Gabriel Sas 12-Mar-13 12:24pm    
276 | 277
277 | 278
278 | 279

in this order
Richard C Bishop 12-Mar-13 12:31pm    
Just do an order by and add desc to the end of what you are ordering by.

You may want to look into Recursive Queries Using Common Table Expressions[^]. From what I gathered from that page CTEs are exactly what you are looking for. There is an elaborate example at the bottom of that page that looks to me as if it would solve your problem.

[Modified]
I realised a bit late that you are talking about MySql, so I had a look and turned up this: Managing Hierarchical Data in MySQL[^]. You may want to skip down to the part about "The Nested Set Model" as this seems to be a better fit to your problem than the "The Adjacency List Model".
[/Modified]

Keep us posted of your findings! :)

Regards,
— Manfred
 
Share this answer
 
v2
found the problem, it's a spelling one, i have put ":" here:
changed this
SQL
(select @op_nr=280, @depth:=0 ) as vars,
to
SQL
(select @op_nr:=280, @depth:=0 ) as vars,
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900