使用内连接和 2 个左连接(带子查询)的 SQL 到 Linq 转换
我有以下查询,它在 SSMS 中运行良好。我使用 LinqPad (C#),但在 LinqToSql 中成功使用左外连接确实令人费解:
SELECT DISTINCT
A.LocID,
V1.PrfValue AS pID,
V2.PrfValue AS sID,
D.DivisionManager,
A.IsApproved,
A.DateCreated
FROM
dbo.Locations AS A
INNER JOIN
dbo.Divisions AS D
ON A.DivisionID = D.DivisionID
LEFT OUTER JOIN
dbo.ValuesInLocations AS V1
ON A.LocID = V1.LocID
AND
V1.PrfID IN (SELECT
PrfID
FROM
dbo.PrfTag
WHERE
(LevelTypeID = 1))
LEFT OUTER JOIN
dbo.ValuesInLocations AS V2
ON A.LocID = V2.LocID
AND
V2.PrfID IN (SELECT
PrfID
FROM
dbo.PrfTag
WHERE
(LevelTypeID = 2))
如您所见,这不是开始工作的最优雅的查询,我同意子查询两个左连接都可以改进。不过,你能帮我翻译一下吗?
I have the following query which works fine in SSMS. Im using LinqPad (C#) but really puzzling to succeed with the left outer join in LinqToSql:
SELECT DISTINCT
A.LocID,
V1.PrfValue AS pID,
V2.PrfValue AS sID,
D.DivisionManager,
A.IsApproved,
A.DateCreated
FROM
dbo.Locations AS A
INNER JOIN
dbo.Divisions AS D
ON A.DivisionID = D.DivisionID
LEFT OUTER JOIN
dbo.ValuesInLocations AS V1
ON A.LocID = V1.LocID
AND
V1.PrfID IN (SELECT
PrfID
FROM
dbo.PrfTag
WHERE
(LevelTypeID = 1))
LEFT OUTER JOIN
dbo.ValuesInLocations AS V2
ON A.LocID = V2.LocID
AND
V2.PrfID IN (SELECT
PrfID
FROM
dbo.PrfTag
WHERE
(LevelTypeID = 2))
As you can see, this isn't the most elegant query to begin work, and I agree that the subquery in both left joins could be improved. However, could you please help me with this translation??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是您的查询的 2 种可能的翻译。我在第一个翻译中使用了 3 个单独的查询,以使其更具可读性。我希望您发现它们很有用。
这是第二种可能的翻译:
Following are 2 possible translations of your query. I uses 3 separate queries in the first translation to make it more readable. I hope you find them useful.
Here is the second possible translation:
在 LINQ 中可能有一些棘手的方法可以做到这一点,但除了内部联接之外,LINQ JOIN 对于任何其他操作都是痛苦的。为了可维护性,我不鼓励对此查询使用 linq。我知道这并不能完全回答您的问题,但我认为您不会得到比该查询更好的答案。
There may be some tricky way to do this in LINQ, but LINQ JOINs are painful for anything other than an inner join. For maintainability, I would discourage the use of linq for this query. I know this doesn't exactly answer your question, but I don't think you're going to get an answer you like that's any better than that query.