将 SQL 子查询转换为 In to Linq Lambda
如何将以下 SQL 语句转换为 Lambda 表达式或 Linq 查询?
以下查询获取每个问题的最新答案。或者换句话说,为每个问题提供最新的答案。
这也将由实体框架执行。
SELECT Answers.*
FROM Answers
Where AnswerID IN
(
SELECT Max(AnswerID) AnswerID
FROM Answers
GROUP BY QuestionID
)
这里是使用 Inner Join 查看上一个查询的另一种方法,
SELECT answers.*
FROM answers
INNER JOIN
(
SELECT Max(answerID) answerID --, QuestionSiteID
FROM answers
GROUP BY QuestionID
) t ON
answers.answerID = t.answerID
我读到 LINQ Contains 方法对于访问 SQL 的查询来说不是最优的。
LINQ to Sql 和 .Contains() 陷阱。
How do I convert the following SQL statement into Lambda Expression or Linq Query?
The following query get the single most recent Answer for each Question. Or to phrase it another way, get each Question with the newest Answer.
Also this will be execute by Entity Framework.
SELECT Answers.*
FROM Answers
Where AnswerID IN
(
SELECT Max(AnswerID) AnswerID
FROM Answers
GROUP BY QuestionID
)
Here another way to look at the previous query using an Inner Join
SELECT answers.*
FROM answers
INNER JOIN
(
SELECT Max(answerID) answerID --, QuestionSiteID
FROM answers
GROUP BY QuestionID
) t ON
answers.answerID = t.answerID
I have read that the LINQ Contains method is sub optimal for queries that access SQL.
LINQ to Sql and .Contains() trap.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你可以使用类似的方法来做到这一点:
这会在生成的 SQL 中产生 CROSS JOIN
另外,你可以在查询的第二部分中使用
join
:这会在 SQL 中产生 INNER JOIN
注意副例 - 上面的答案做出了合理的假设,即
AnswerID
是Answers
的主键 - 如果您碰巧有一个以 (AnswerID 、 QuestionID),那么您将需要同时加入 AnswerID 和 QuestionID,例如:有关此替代表设计的更多讨论,请参阅评论线索...
I think you could do this using something like:
This results in a CROSS JOIN in the generated SQL
Also, you could use
join
in the second part of the query:This results in a INNER JOIN in the SQL
Note for side cases - the above answers make the reasonable assumption that
AnswerID
is the primary key ofAnswers
- if you happen to have instead a table design which is keyed on (AnswerID, QuestionID) then you will need to join by both AnswerID and QuestionID like:See the comment trail for more discussion on this alternate table design...
您可以使用
let
语句来选择每个 QuestionID 组的第一个答案:编辑:Linq2Sql 将上述查询转换为 N+1 数据库调用。该查询仅被转换为一个 SQL 查询:
让我想知道 Linq2Sql 应该在哪些方面比 SQL 更简单。
You could use a
let
statement to select the first answer per QuestionID group:EDIT: Linq2Sql translates the above query into a N+1 database calls. This query gets translated to just one SQL query:
Makes me wonder in what way Linq2Sql is supposed to be simpler than SQL.
尝试使用这个查询:
我刚刚在探查器中检查了查询,它生成单个 SQL 查询(丑陋的查询):
Try to use this query:
I just checked the query in profiler and it produces single SQL query (the ugly one):