简体   繁体   English

为什么MySQL在简单的select语句上使用表别名会出错?

[英]Why MySQL error using table alias on a simple select statement?

I'm using phpmyadmin to test out some MySQL queries. 我正在使用phpmyadmin来测试一些MySQL查询。 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 (works) SELECT * FROM table1 AS tablealias1 (有效)

SELECT * FROM table1 GROUP BY userid (works) SELECT * FROM table1 GROUP BY userid (有效)

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 GROUP BY userid AS tablealias1 (错误:# SELECT * FROM table1 GROUP BY userid AS tablealias1您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取在'AS tablealias1 LIMIT 0,25'附近使用的正确语法第1行)

SELECT * FROM table1 WHERE userid=1 (works) SELECT * FROM table1 WHERE userid=1 (有效)

SELECT * FROM table1 WHERE userid=1 AS tablealias1 (same error as above) SELECT * FROM table1 WHERE userid=1 AS tablealias1 (与上述错误相同)

(SELECT * FROM table1 WHERE userid=1) AS tablealias1 (same error as above) (SELECT * FROM table1 WHERE userid=1) AS tablealias1 (与上述错误相同)

You alias things to: 您将事物别名为:

  • rename the column display's name 重命名列显示的名称
  • give it a reference name for later use elsewhere in the query statement (whether you use it explicitly or implicitly--as long as it could be used elsehere) 给它提供一个引用名称,以供以后在查询语句中的其他位置使用(无论是显式还是隐式使用-只要可以在此处其他位置使用它)

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. 除非在子查询中使用结果集,否则您不能为结果集添加别名,然后需要一个别名来引用它。

This will work: 这将起作用:

 Select * FROM (SELECT * FROM table1 WHERE userid=1) AS tablealias1

as it implies 正如它所暗示的

  Select tablealias1.* FROM (SELECT * FROM table1 WHERE userid=1) AS tablealias1

Alone, this is garbage: 一个人,这是垃圾:

  (SELECT * FROM table1 WHERE userid=1) AS tablealias1

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

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