简体   繁体   English

MySQL子查询怪癖或预期的行为?

[英]MySQL subquery quirk or expected behaviour?

I'm trying to gain more knowledge concerning the MySQL database and I'm hoping someone over here might be able to explain to me the following issue as I cant find much about this particular behavior anywhere: 我试图获得有关MySQL数据库的更多知识,我希望这里的人可以向我解释以下问题,因为我在任何地方都无法找到有关此特定行为的更多信息:

This works: 这有效:

SELECT justaname FROM (SELECT productName AS justaname FROM kclbs_products) sdfsdfsd

While this doesnt: 虽然这没有:

SELECT justaname FROM (SELECT productName AS justaname FROM kclbs_products) 

This really puzzle's me and I believe it to be a quirk because whatever I turn the string 'sdfsdfsd' into doesn't matter, the query still works, even when its just a single character (or a very large sequence of characters for that matter). 这确实让我感到困惑,我相信这是一个怪癖,因为无论我将字符串sdfsdfsd变成什么都没有关系,即使它只是一个字符(或与此相关的非常大的字符序列),查询仍然有效)。 This 'issue' doesn't represent a problem to me currently but I would really like to know the 'why' behind it to be able to deal with this kinda behavior anywhere in the possible future should I ever have to. 目前,这个“问题”对我来说并不构成问题,但我真的很想知道它背后的“原因”,以便在将来可能需要的任何地方应对这种行为。

Thanks in advance. 提前致谢。

[UPDATE] Two users have helped providing me with the answer to my question, so its solved, and thanks! [更新]两位用户帮助向我提供了我的问题的答案,因此问题已得到解决,谢谢!

It subquery name 它的子查询名称

SELECT ... FROM (subquery) [AS] name ...

Here is reference from mysql docs 这是来自mysql文档的参考
The [AS] name clause is mandatory, because every table in a FROM clause must have a name. [AS] name子句是强制性的,因为FROM子句中的每个表都必须有一个名称。 Any columns in the subquery select list must have unique names. 子查询选择列表中的任何列都必须具有唯一的名称。

For futher info use https://dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html 有关更多信息,请使用https://dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html

This is not related to MySQL, and its a rule in all DBMS's. 这与MySQL无关,在所有DBMS中都是这样。 if you use subquery in FROM clause you must alias it. 如果在FROM子句中使用子查询,则必须为其加上别名。

When you write something after subquery (like sdfsdfsd), DBMS consider it as alias name of table derived from subquery. 当您在子查询之后编写某些内容时(例如sdfsdfsd),DBMS会将其视为从子查询派生的表的别名

You can see some information about subqueries in FROM clause in: 您可以在以下位置的FROM子句中看到有关子查询的一些信息:

  1. https://dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html https://dev.mysql.com/doc/refman/5.7/zh-CN/from-clause-subqueries.html

and

  1. http://www.geeksengine.com/database/subquery/subquery-in-from-clause.php http://www.geeksengine.com/database/subquery/subquery-in-from-clause.php
  2. it also explained in subquery in FROM must have an alias 它还在FROM中的子查询中说明了必须具有别名

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

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