Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

tricky many to many query Expand / Collapse
Author
Message
Posted Monday, February 11, 2013 1:45 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, January 21, 2014 6:39 AM
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
Post #1418253
Posted Monday, February 11, 2013 2:38 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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!
Post #1418267
Posted Monday, February 11, 2013 2:59 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, January 21, 2014 6:39 AM
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!
Post #1418273
Posted Monday, February 11, 2013 3:02 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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!
Post #1418275
Posted Thursday, April 4, 2013 4:26 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, January 21, 2014 6:39 AM
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
Post #1438709
Posted Thursday, April 4, 2013 6:05 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, July 21, 2014 2:19 AM
Points: 246, Visits: 1,166
Thanks Dwain,

This does solve all routeplanning problems

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.
Post #1438737
Posted Thursday, April 4, 2013 6:34 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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!
Post #1438750
Posted Thursday, April 4, 2013 6:37 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
ben.brugman (4/4/2013)
Thanks Dwain,

This does solve all routeplanning problems

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!
Post #1438751
Posted Thursday, April 4, 2013 8:28 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, January 21, 2014 6:39 AM
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
Post #1438830
Posted Thursday, April 4, 2013 9:23 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, January 21, 2014 6:39 AM
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) )
)
Post #1438862
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse