SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


tricky many to many query


tricky many to many query

Author
Message
kevin 20860
kevin 20860
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 34
I have a complex query to put together and need some help. I have a table like the one below which is many to many. Essentially two primary columns (assume named left and right)

left right
---- -------
1 .... 2
2 .... 3
3 .... 4
1 .... 4
1 .... 5
5 .... 4
6 .... 4

Assuming I know the id on the left (1) and the id on the right (4) I need to find all paths for the combination and return them in a delimited string as below. Something like:

1/2/3/4 but also 1/4 and 1/5/4

The number of paths is only likely to be 3 or 4 and no more. I'm guessing I need to do something recursive and save the path at each level.

Any ideas on a good (and fast) way to do this?
thanks
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)

Group: General Forum Members
Points: 7527 Visits: 6431
Something like this perhaps?


DECLARE @Paths TABLE ([left] INT, [right] INT)

INSERT INTO @Paths
SELECT 1 , 2
UNION ALL SELECT 2 , 3
UNION ALL SELECT 3 , 4
UNION ALL SELECT 1 , 4
UNION ALL SELECT 1 , 5
UNION ALL SELECT 5 , 4
UNION ALL SELECT 6 , 4

;WITH C AS (
SELECT n=1,[left], [right]
,[Path]=CAST([left] AS VARCHAR(8000)) + '/' + CAST([right] AS VARCHAR(8000))
FROM @Paths
UNION ALL
SELECT n+1, C.[right], a.[right], [Path] + '/' + CAST(a.[right] AS VARCHAR(8000))
FROM C
INNER JOIN @Paths a ON C.[right] = a.[left]
)
SELECT *
FROM C
WHERE LEFT([Path], 1) = '1' AND RIGHT([Path], 1) = '4'





My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
kevin 20860
kevin 20860
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 34
thank you. I had something similar to that so was heading in the right direction but as they say the devil is in the details.

I'll check it against my table and see what I get.
thanks,

PS. nice fish!
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)

Group: General Forum Members
Points: 7527 Visits: 6431
kevin 20860 (2/11/2013)
thank you. I had something similar to that so was heading in the right direction but as they say the devil is in the details.

I'll check it against my table and see what I get.
thanks,

PS. nice fish!


You're welcome. Obviously what I did won't handle IDs once they get to be greater than 9, but I think you can probably figure out a way to handle that (add leading zeroes).

Fish: 45kg Mekong Catfish + Thanks.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
kevin 20860
kevin 20860
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 34
Dwain (or anyone!)

Is there any way to detect an prevent this crashing on a circular reference? I need to have it support a circular ref but using this method above causes an error.

thanks
ben.brugman
ben.brugman
Ten Centuries
Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)

Group: General Forum Members
Points: 1064 Visits: 2391
Thanks Dwain,

This does solve all routeplanning problems :-P

Well at least it is a good start to solve all routeplanning problems.

Thanks
Ben

Sidestep:
I have often been thinking how I would solve a routeplanning problem using SQL-server. And more important how I would optimize the routeplanning problem.
Your solution is a fairly elegant solution to show that this can be done easily if the number number of nodes is limited.
I have designed (but not build) algoritms for the fasted and the shortest routes. And also have made optimisation to find a solution as fast as possible, but which is not guaranteed to be the best solution.
And solutions which work fairly wel and guarantee the best solution which can be calculated.
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)

Group: General Forum Members
Points: 7527 Visits: 6431
kevin 20860 (4/4/2013)
Dwain (or anyone!)

Is there any way to detect an prevent this crashing on a circular reference? I need to have it support a circular ref but using this method above causes an error.

thanks


The short answer is I don't think so. It might be possible to remove circular references if you can detect them but that would be challenging depending on the number of nodes to traverse.

I have developed a looping solution that might work. Honestly this thread doesn't really cause me to recollect much as its nearly 6 months old. I do recognize the solution I gave from my article on generate n-Tuples (http://www.sqlservercentral.com/articles/sql+n-Tuples/89809/).

I am not 100% certain the looping solution would be applicable but I'll give you a hint. I used an EXCEPT to remove cases when a circular reference was encountered.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)SSCertifiable (7.5K reputation)

Group: General Forum Members
Points: 7527 Visits: 6431
ben.brugman (4/4/2013)
Thanks Dwain,

This does solve all routeplanning problems :-P

Thanks
Ben



If it did then I'd be well on my way to fortune and glory. Alas, that is not the case.

The article in my link on recursive CTEs below has a solution to the classic transportation problem. And there are probably ways to improve upon it, given sufficient time and energy.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
kevin 20860
kevin 20860
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 34
Cheers Dwain. I'll take a look at your link and see if I can work it into my solution. This stuff just wrecks my head :-)
kevin 20860
kevin 20860
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 34
Ok not sure If I've got it right but if I add "where a.left not in (select id from dbo.ufn_Split(c.path) )" after the Inner join it appears to work ok. The split function takes the comma delimited list and returns one item per row.

I'll do a lot more checking to make sure it works in all situations. Might also change the "in" to "exists" as that is probably more effecient.


;WITH C AS (
SELECT n=1,[left], [right]
,[Path]=CAST([left] AS VARCHAR(8000)) + '/' + CAST([right] AS VARCHAR(8000))
FROM @Paths
UNION ALL
SELECT n+1, C.[right], a.[right], [Path] + '/' + CAST(a.[right] AS VARCHAR(8000))
FROM C
INNER JOIN @Paths a ON C.[right] = a.[left]
where a.left not in (select id from dbo.ufn_Split(c.path) )
)
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search