问题描述
与常规 SQL 查询不同,为什么 linq to sql 查询以 FROM 关键字开头?
Why do linq to sql queries starts with the FROM keyword unlike regular SQL queries?
推荐答案
LINQ 模仿 SQL 中的逻辑查询处理:
LINQ mimics Logical Query processing in SQL you have:
8. SELECT 9. DISTINCT 11. TOP 1. FROM 2. ON 3. JOIN 4. WHERE 5. GROUP BY 6. WITH CUBE/ROLLUP 7. HAVING 10. ORDER BY 12. OFFSET/FETCH
但实际上它是这样执行的:
But actually it executed like:
1. FROM 2. ON 3. JOIN 4. WHERE 5. GROUP BY 6. WITH CUBE/ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10. ORDER BY 11. TOP 12. OFFSET/FETCH
很多人都没有意识到这一点,并犯了一些简单的错误,例如:
Many people is not aware of it and made simple mistakes like:
SELECT col AS alias_name FROM tab WHERE aliass_name > 10;
并询问为什么它不起作用.因为他们假设订单就像他们写的一样.LINQ 在这方面做得更好.
And ask why it doesn't work. Because they assume that the order is like they write it. LINQ is better at this matter.
另见逻辑查询处理和BOL:
SELECT 语句的逻辑处理顺序
以下步骤显示逻辑处理顺序,或绑定order,用于 SELECT 语句.此顺序确定对象何时在一个步骤中定义的内容可用于后续的子句脚步.例如,如果查询处理器可以绑定(访问)在 FROM 子句中定义的表或视图、这些对象及其列可用于所有后续步骤.反过来,因为 SELECT 子句是第 8 步,所以任何列别名或派生该子句中定义的列不能被前面的引用条款.但是,它们可以被后续子句引用,例如ORDER BY 子句.请注意,实际的物理执行语句由查询处理器决定,顺序可能会有所不同从此列表中.
The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
FROM ON JOIN WHERE GROUP BY WITH CUBE or WITH ROLLUP HAVING SELECT DISTINCT ORDER BY TOP