舉例來說,我需要從 pc, laptop, printer 三個 Table 取最貴的產品出來,想像的寫法可能是如此:
SELECT model FROM ( SELECT * FROM pc UNION SELECT * FROM laptop UNION SELECT * FROM printer ) WHERE price=( SELECT MAX(price) FROM ( SELECT * FROM pc UNION SELECT * FROM laptop UNION SELECT * FROM printer ) )
我們會發現三個 table 的 UNION 被重複使用,非常麻煩。
這時我們可以將這三個 table 的 UNION 暫存成 CTE,藉由以下的方式。
WITH product AS ( SELECT * FROM pc UNION SELECT * FROM laptop UNION SELECT * FROM printer ) SELECT model FROM product WHERE price=( SELECT MAX(price) FROM product )
TADA~~~是不是簡單明瞭又方便勒?