[英]ORDER BY works only with column alias
So, I have this query 所以,我有这个问题
SELECT
NOTES,
DATECREATED,
DATEMODIFIED,
*
FROM myTable
WHERE
USERCREATEDBY = 465
AND NOTES LIKE ' :%'
ORDER BY DATECREATED
and it throws this error Ambiguous column name 'DATECREATED'
. 并抛出此错误
Ambiguous column name 'DATECREATED'
。
I see nothing wrong with my query and I found a fix for this in the form of adding an alias to column DATECREATED
, like DATECREATED a
, and ordering by alias, ORDER BY a
. 我发现我的查询没有任何问题,我发现了一个修复方法,即在
DATECREATED
列中添加别名,如DATECREATED a
,并按别名ORDER BY a
排序。
I do not understand why this happens and I am very curious to know why. 我不明白为什么会这样,我很想知道为什么。
It's probably because you're selecting DATECREATED twice, once as a column and once in * 这可能是因为你选择DATECREATED两次,一次是作为一列,一次是*
SELECT *
FROM myTable
WHERE
USERCREATEDBY = 465
AND NOTES LIKE ' :%'
ORDER BY DATECREATED
Should work fine 应该工作正常
Because DATECREATED
appears in the SELECT
list twice. 因为
DATECREATED
两次出现在SELECT
列表中。
In this case both instances refer to the same underlying column but it is still invalid syntax. 在这种情况下,两个实例都引用相同的基础列,但它仍然是无效的语法。 In general you could have two projected columns with the same name that refer to different columns.
通常,您可以使用两个具有相同名称的投影列来引用不同的列。
SELECT
DATECREATED AS D,
DATEMODIFIED AS D
FROM myTable
ORDER BY D /*Obviously ambiguous*/
By the way applying any sort of expression to the ORDER BY DATECREATED
resolves the ambiguity as it will then be resolved against the column in the base table. 顺便说一下,将任何类型的表达式应用于
ORDER BY DATECREATED
可以解决歧义,因为它将针对基表中的列进行解析。
CREATE TABLE myTable
(
NOTES VARCHAR(50),
DATECREATED DATETIME,
DATEMODIFIED DATETIME
)
SELECT
NOTES,
DATECREATED,
DATEMODIFIED,
*
FROM myTable
ORDER BY DATECREATED + 0 /*Works fine*/
I just mention this in passing however. 我只是顺便提一下。 It is definitely not a suggestion that you should do this.
绝对不是你应该这样做的建议。
Well, if your table contains this column DATECREATED
, then you're selecting this column twice with the above SELECT
- once explicitly, once implicitly by using the *
. 好吧,如果你的表包含
DATECREATED
这个列,那么你用上面的SELECT
选择这个列两次 - 一次显式,一次隐式使用*
。
So your result set now contains two columns called DATECREATED
- which one do you want ORDER BY
to be applied to?? 所以你的结果集现在包含两个名为
DATECREATED
列 - 你想要将ORDER BY
应用DATECREATED
一列 ?
Either explicitly specify the complete column list that you need, or then at least provide an alias for the DATECREATED
column: 要么显式指定所需的完整列列表,要么至少为
DATECREATED
列提供别名:
SELECT
NOTES,
SecondDateCreated = DATECREATED,
DATEMODIFIED,
*
FROM myTable
WHERE
USERCREATEDBY = 465
AND NOTES LIKE ' :%'
ORDER BY DATECREATED
It seems ORDER BY
can't understand which DATECREATED
column should be used for ordering. 似乎
ORDER BY
无法理解应该使用哪个DATECREATED
列进行排序。 You specified it twice in SELECT
clause. 您在
SELECT
子句中指定了两次。
try this: 尝试这个:
SELECT
NOTES,
DATECREATED,
DATEMODIFIED,
*
FROM myTable
WHERE
USERCREATEDBY = 465
AND NOTES LIKE ' :%'
ORDER BY 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.