Sql syntax: select without from clause as subquery in select (subselect)

自古美人都是妖i 提交于 2019-12-05 03:46:28
Jorge Campos

This is the default behavior for the SQL language and it is defined on the SQL ANSI 2011 over ISO/IEC 9075-1:2011(en) documentation. Unfortunately it is not open. This behavior is described on the section 4.11 SQL-Statements.

This behavior happens because the databases process the select comand without the from clause, therefore if it encounters:

select id, (select name) from some 

It will try to find that name field as a column of the outer queries to process.

Fortunately I remember that some while ago I've answered someone here and find a valid available link to an SQL ANSI document that is online in FULL but it is for the SQL ANSI 99 and the section may not be the same one as the new document. I think, did not check, that it is around the section 4.30. Take a look. And I really recommend the reading (I did that back in the day).

Database Language SQL - ISO/IEC 9075-2:1999 (E)

What you within your first query is a correlated subquery which simply returns the name column from the table t. no actual subquery needs to run here (which is what your EXPLAIN is telling you).

In a SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query.

https://en.wikipedia.org/wiki/Correlated_subquery

SELECT id, (SELECT name) FROM t

is the same as

SELECT id, (SELECT t.name) FROM t

Your 2nd query

SELECT id, (SELECT name FROM t AS t1 where t1.id=t2.id) FROM t AS t2

Also contains correlated subquery but this one is actually running a query on table t to find records where t1.id = t2.id.

It's not standard. In oracle,

select 1, (select 2) 
from dual

Throws error, ORA-00923: FROM keyword not found where expected

How can you be sure of your results? Get a better understanding of what the query is supposed to acheive before you write it. Even the exetended version in the question does not make any sense.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!