为什么在简单的 select 语句上使用表别名时 MySQL 会出错? [英] Why MySQL error using table alias on a simple select statement?
问题描述
我正在使用 phpmyadmin 来测试一些 MySQL 查询.我正在尝试编写一个更大的嵌套查询,该查询由于无法识别的表别名而失败,因此我正在尝试调试它的较小部分.但是,有时我尝试使用表别名时会遇到令人困惑的错误.
I'm using phpmyadmin to test out some MySQL queries. I'm trying to write a larger, nested query, which is failing due to an unrecognized table alias, so I'm trying to debug smaller parts of it. However, I'm getting confusing errors when I try to use table aliases sometimes.
你能解释为什么其中一些查询会抛出错误吗?
Can you explain why some of these queries throw errors?
SELECT * FROM table1 AS tablealias1
(有效)
SELECT * FROM table1 GROUP BY userid
(有效)
SELECT * FROM table1 GROUP BY userid AS tablealias1
(错误:#1064 - 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册以了解要使用的正确语法'AS tablealias1 附近LIMIT 0, 25' 在第 1 行 )
SELECT * FROM table1 GROUP BY userid AS tablealias1
(error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS tablealias1
LIMIT 0, 25' at line 1 )
SELECT * FROM table1 WHERE userid=1
(有效)
SELECT * FROM table1 WHERE userid=1 AS tablealias1
(错误同上)
(SELECT * FROM table1 WHERE userid=1) AS tablealias1
(错误同上)
推荐答案
您将事物别名为:
- 重命名列显示名称
- 给它一个引用名称,以便以后在查询语句的其他地方使用(无论是显式还是隐式使用——只要它可以在其他地方使用)
如果您两者都不做,则别名毫无意义.除非在子查询中使用,否则您不能为结果集设置别名,然后您需要一个别名来引用它.
If you're not doing either, an alias makes no sense. You can't alias a result set unless it's used inside a subquery, then you need an alias to reference it.
这会起作用:
Select * FROM (SELECT * FROM table1 WHERE userid=1) AS tablealias1
顾名思义
Select tablealias1.* FROM (SELECT * FROM table1 WHERE userid=1) AS tablealias1
独自一人,这是垃圾:
(SELECT * FROM table1 WHERE userid=1) AS tablealias1
这篇关于为什么在简单的 select 语句上使用表别名时 MySQL 会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!