MySQL 按先前声明的别名进行分组,我该如何将其包装起来? '或`
我有一个 SQL 查询,它在 SELECT 语句中有一个别名
选择 CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'
稍后,我想在我的 group by 语句中引用此内容。
我有点困惑...我应该用反引号、单引号将其括起来,还是直接将其展开到 group by
GROUP BY 中 ``QuarterYear
还是我应该这样做?: 分组依据 “QuarterYear”
还是这个?: 分组依据 季度年
I have an SQL query that has an alias in the SELECT statement
SELECT
CONCAT(YEAR(r.Date),_utf8'-',_utf8'Q',QUARTER(r.Date)) AS 'QuarterYear'
Later, I want to refer to this in my group by statement.
I'm a little confused...should I wrap this with backticks, single quote or just leave it unwrapped int he group by
GROUP BY
``QuarterYear
or should I do this?:
GROUP BY
'QuarterYear'
or just this?:
GROUP BY
QuarterYear
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用反引号转义别名或列名称,但仅当您的列具有保留字作为其名称(即
timestamp
)时才需要,因此您不需要这样做。避免使用保留字,这样您就永远不需要用反引号转义列名。你不应该使用单引号来包裹列名,这仅适用于数据。
编辑:您不能按组列的别名进行分组(即
MIN()
、MAX()
、COUNT()< /code> 等),但可以使用函数别名(即
CONCAT()
)。You can escape aliases or column names using a backtick but it's only required when your column has a reserved word as its name (i.e.
timestamp
), so you don't need to. Avoid using reserved words instead, so you'll never need to escape column names with backticks.You should never use single quotes to wrap column names, this is only for data.
EDIT: You can't group by aliases of group columns (i.e.
MIN()
,MAX()
,COUNT()
etc) but using aliases of functions (i.e.CONCAT()
) you can.不幸的是,您无法使用别名,因为别名在 GROUP BY 中尚不可用。不过,您可以使用列号:
在这种特殊情况下,您可以只使用 DISTINCT 修饰符:
Unfortunatelly, you can not use the alias because the alias is not yet available in GROUP BY. You can use the number of the column though:
In this particular case you can just use DISTINCT modifier: