iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

子查詢(Sub query)

在資料庫查詢中,子查詢(Subquery)是一個非常有用的技術,可從多個表中擷取所需的資料,編寫更複雜的查詢。子查詢可以返回一個值、一個列或一個資料集,並且可以用於WHERE、FROM、SELECT、JOIN等子句中。子查詢通常用於從多個表中擷取資料,或者在查詢中使用聚合函數。

【Example】

  1. 子查詢用於 select 子句
select c.name, (select 1 from dual) "no.1"
from city c
where c.population > 120000
and c.countrycode = 'USA'
;
-- output:
-- Scottsdale 1
-- Corona 1
-- Concord 1
  1. 子查詢用於 from 子句
select c.ID, c.name, a.code
from (
    select 'Rose' name, 123 ID from dual
    union all
    select 'Angela' name, 456 ID from dual
) C, (
    select 'Rose' name, 'A' code from dual
    union all
    select 'Angela' name, 'B' code from dual
) A
where 1=1
and A.name = c.name
;
-- output:
-- 123 Rose A
-- 456 Angela B
  1. 子查詢用於 where子句
select c.*
from (
    select 'Rose' name, 123 ID from dual
    union all
    select 'Angela' name, 456 ID from dual
) C
where 1=1
and c.name in (
    select A.name from Contests A
)
;
-- output:
-- Rose 123
-- Angela 456

With子句

With就是將sub query重新命名為一張新的table, 後續的查詢與法可直接使用rename的table name做查詢。

with test_table as (
    select 'Rose' name, 'green' color from dual
    union all
    select 'Angela' name, 'red' color from dual
)
select t.*
from test_table t
;

Reference


上一篇
Day 5 基礎-典型語法+字串常用函式
下一篇
Day 7 基礎-集合運算
系列文
不居功的系統隱士 - 30天由淺入深學SQL14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言