简体   繁体   English

我们可以在 MySQL 的 ORDER BY 子句中使用别名字段吗?

[英]Can we use aliased field to use in ORDER BY clause in MySQL?

Can we use aliased field name in ORDER BY clause?我们可以在ORDER BY子句中使用别名字段名称吗?

For example:例如:

SELECT id, name AS firstname
FROM users
ORDER BY firstname


Is it possible?是否有可能? When I tried this it errored out.当我尝试这个时,它出错了。

An alias can be used in a query select list to give a column a different name.可以在查询选择列表中使用别名来为列指定不同的名称。 You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column.您可以在 GROUP BY、ORDER BY 或 HAVING 子句中使用别名来引用该列。

Checkhere .检查这里

您不能在 MS SQL SERVER 的 GROUP BY 子句中使用别名

为了告诉您可以在某些子句中使用别名,请检查 SQL 处理查询的顺序,如下所示: -from -where -group by -have -order by

Yes, you can certainly use column aliases in your "order by" clause.是的,您当然可以在“order by”子句中使用列别名。

You can verify it works with the built-in mySql "user" table:您可以验证它是否适用于内置的 mySql“用户”表:

 select User as name,Host from user order by name;

If it "errored out", then something else must have been wrong with your query.如果它“出错”,那么您的查询肯定有其他问题。 Please cut/paste the exact error message.请剪切/粘贴确切的错误消息。

Try with this one, I have added back-ticks to column name and table Because name is the reserved word :试试这个,我在列名和表中添加了反引号,因为 name 是保留字:

SELECT `id`, `name` AS firstname
FROM `users`
ORDER BY firstname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM