邏輯條件 - Amazon Redshift

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

邏輯條件

邏輯條件會合併兩個條件的結果,來產生單一結果。所有的邏輯條件都是二元運算子,具有 Boolean 傳回類型。

語法

expression { AND | OR } expression NOT expression

邏輯條件使用三種值的布林邏輯,其中 null 值代表未知的關係。下表說明邏輯條件的結果,其中 E1E2 表示表達式:

E1 E2 E1 AND E2 E1 OR E2 NOT E2
TRUE TRUE TRUE TRUE FALSE
TRUE FALSE FALSE TRUE TRUE
TRUE UNKNOWN UNKNOWN TRUE UNKNOWN
FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE
FALSE UNKNOWN FALSE UNKNOWN
UNKNOWN TRUE UNKNOWN TRUE
UNKNOWN FALSE FALSE UNKNOWN
UNKNOWN UNKNOWN UNKNOWN UNKNOWN

NOT 運算子會在 之前進行評估AND,而AND運算子會在 OR 運算子之前進行評估。如果使用任何括號,就可以覆蓋這個預設的評估順序。

範例

下列範例USERNAME會從使用者喜歡拉斯維加斯和運動的USERS資料表傳回 USERID和 :

select userid, username from users where likevegas = 1 and likesports = 1 order by userid; userid | username --------+---------- 1 | JSG99FHE 67 | TWU10MZT 87 | DUF19VXU 92 | HYP36WEQ 109 | FPL38HZK 120 | DMJ24GUZ 123 | QZR22XGQ 130 | ZQC82ALK 133 | LBN45WCH 144 | UCX04JKN 165 | TEY68OEB 169 | AYQ83HGO 184 | TVX65AZX ... (2128 rows)

下一個範例USERNAME會從使用者喜歡拉斯維加斯、運動或兩者的USERS資料表傳回 USERID和 。此查詢會傳回前一個範例的所有輸出資料,加上只喜歡拉斯維加斯或運動的使用者。

select userid, username from users where likevegas = 1 or likesports = 1 order by userid; userid | username --------+---------- 1 | JSG99FHE 2 | PGL08LJI 3 | IFT66TXU 5 | AEB55QTM 6 | NDQ15VBM 9 | MSD36KVR 10 | WKW41AIW 13 | QTF33MCG 15 | OWU78MTR 16 | ZMG93CDD 22 | RHT62AGI 27 | KOY02CVE 29 | HUH27PKK ... (18968 rows)

下列的查詢在 OR 條件周圍加上括號,以找出在紐約或加州上演「馬克白」的場地:

select distinct venuename, venuecity from venue join event on venue.venueid=event.venueid where (venuestate = 'NY' or venuestate = 'CA') and eventname='Macbeth' order by 2,1; venuename | venuecity ----------------------------------------+--------------- Geffen Playhouse | Los Angeles Greek Theatre | Los Angeles Royce Hall | Los Angeles American Airlines Theatre | New York City August Wilson Theatre | New York City Belasco Theatre | New York City Bernard B. Jacobs Theatre | New York City ...

如果移除此範例中的括號,將會改變查詢的邏輯和結果。

下列的範例使用 NOT 運算子:

select * from category where not catid=1 order by 1; catid | catgroup | catname | catdesc -------+----------+-----------+-------------------------------------------- 2 | Sports | NHL | National Hockey League 3 | Sports | NFL | National Football League 4 | Sports | NBA | National Basketball Association 5 | Sports | MLS | Major League Soccer ...

下列範例使用 NOT 條件,後接 AND 條件:

select * from category where (not catid=1) and catgroup='Sports' order by catid; catid | catgroup | catname | catdesc -------+----------+---------+--------------------------------- 2 | Sports | NHL | National Hockey League 3 | Sports | NFL | National Football League 4 | Sports | NBA | National Basketball Association 5 | Sports | MLS | Major League Soccer (4 rows)