Reputation: 10324
I need to implement this in Linq-to-sql
SELECT DISTINCT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s ON c.Room = s.Entry_Bar_Code
OR c.HomeRoom = s.Entry_Bar_Code
WHERE s.id = 1021645
All the research I've done on this says that linq-to-sql can't support an "OR" multiple join, and the suggestions are to instead do two joins like this:
SELECT DISTINCT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s ON c.Room = s.Entry_Bar_Code
LEFT OUTER JOIN dbo.Lab_Space s2 ON c.HomeRoom = s2.Entry_Bar_Code
WHERE s.id = 1021645
Those aren't actually the same query though as they'll return different results. Short of just putting the raw SQL into my C# program at this point, is there any way to accomplish the above?
Upvotes: 1
Views: 455
Reputation: 175596
Let's start from beginning. If you use WHERE
with column from OUTER JOIN
table it means that your query:
SELECT DISTINCT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s ON c.Room = s.Entry_Bar_Code
OR c.HomeRoom = s.Entry_Bar_Code
WHERE s.id = 1021645
is logically equivalent to:
SELECT DISTINCT c.*
FROM dbo.Collector_Capital_Equipment c
JOIN dbo.Lab_Space s
ON c.Room = s.Entry_Bar_Code
OR c.HomeRoom = s.Entry_Bar_Code
WHERE s.id = 1021645;
And this could be achieved with CROSS JOIN
(pseudocode):
var q = from c in Collector_Capital_Equipment
from s in Lab_Space
where s.id == 1021645
&& (s.Entry_Bar_Code == c.Room || c.HomeRoom == s.Entry_Bar_Code)
select ...
I assume that you really want to generate query:
SELECT DISTINCT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s
ON (c.Room = s.Entry_Bar_Code OR c.HomeRoom = s.Entry_Bar_Code)
AND s.id = 1021645
which could be represented as:
SELECT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s
ON c.Room = s.Entry_Bar_Code AND s.id = 1021645
INTERSECT
SELECT c.*
FROM dbo.Collector_Capital_Equipment c
LEFT OUTER JOIN dbo.Lab_Space s
ON c.HomeRoom = s.Entry_Bar_Code AND s.id = 1021645
And above query could be achieved with LINQ using set operators.
Upvotes: 1
Reputation: 1
I don't think I've ever seen someone use an OR clause on a join before. Does MS SQL Server even support that in SQL?
I'd probably just split this off into two queries, to be honest.
SELECT entry_bar_code
FROM dbo.Lab_Space WHERE id = 1021645;
With the result from that being fed into
SELECT DISTINCT *
FROM dbo.Collector_Capital_Equipment
WHERE c.room == <barcode> OR c.homeRoom == <barcode>
Upvotes: 0