Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we write subquery in between SELECT and FROM

i want to know, how to write subquery in between SELECT and FROM as

SELECT Col_Name,(Subquery) 
  From Table_Name 
 Where Some_condition
like image 322
Mohsin Avatar asked Mar 12 '10 06:03

Mohsin


2 Answers

This:

SELECT y.col_name,
       (SELECT x.column
          FROM TABLE x) AS your_subquery
  FROM TABLE y
 WHERE y.col = ?

...is a typical subquery in the SELECT clause. Some call it a "subselect". This:

SELECT y.col_name,
       (SELECT x.column
          FROM TABLE x
         WHERE x.id = y.id) AS your_subquery
  FROM TABLE y
 WHERE y.col = ?

...is a correlated subquery. It's correlated because the subquery result references a table in the outer query (y in this case).

Effectively, just write whatever additional SELECT statement you want in the SELECT clause, but it has to be surrounded by brackets.

like image 156
OMG Ponies Avatar answered Nov 12 '22 09:11

OMG Ponies


you can do it, but you must use an alias for the subquery

SELECT Col_Name,(Subquery) as S
  From Table_Name 
 Where Some_condition
like image 23
Iulian Avatar answered Nov 12 '22 10:11

Iulian