子查詢

 

子查詢有三種型式

一、子句用在 from 後面 (推薦)

select b.* from
(
    select a.* from
    (
        select * from Employees
    ) a
) b

 

二、子句用在 select 後面

SELECT A_id, A_name,
    (SELECT COUNT(*) FROM tableB WHERE tableB.A_id=tableA.A_id) AS B_count,  
    (SELECT COUNT(*) FROM tableC WHERE tableC.A_id=tableA.A_id) AS C_count,  
FROM tableA;

 

三、子句用在 where 後面

select count( * ) as 訂單數 
from orders
where customerID = (select id from Customers where name = 'apple')

 

參考資料:

SQL迴圈實作 -1.慣用寫法