我需要在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
我对此所做的所有研究都表明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
LEFT OUTER JOIN dbo.Lab_Space s2 ON c.HomeRoom = s2.Entry_Bar_Code
WHERE s.id = 1021645
尽管这些查询将返回不同的结果,但它们实际上不是相同的查询。到目前为止,除了将原始SQL放入我的C#程序之外,还有什么方法可以完成上述工作?
答案 0 :(得分:1)
让我们从头开始。如果您将WHERE
表中的列与OUTER JOIN
一起使用,则意味着您的查询:
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
在逻辑上等同于:
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;
这可以通过CROSS JOIN
(伪代码)来实现:
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 ...
我假设您确实要生成查询:
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
可以表示为:
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
以上查询可以使用LINQ使用集合运算符实现。
答案 1 :(得分:0)
我认为我以前从未见过有人在联接上使用OR子句。 MS SQL Server甚至在SQL中支持吗?
说实话,我可能会将其分为两个查询。
SELECT entry_bar_code
FROM dbo.Lab_Space WHERE id = 1021645;
将结果输入
SELECT DISTINCT *
FROM dbo.Collector_Capital_Equipment
WHERE c.room == <barcode> OR c.homeRoom == <barcode>