假設我有一個全域引數param_filtered,其值可以是 0 或 1,并且我已經創建了表main,transactions并且transactions_filtered所有三個表都回傳相同數量的欄位
現在我正在嘗試對表進行UNION ALL查詢,但我需要 UNION ALLtransactions或transactions_filtered基于引數條件
我努力了
SELECT * FROM main
UNION ALL
CASE WHEN param_filtered > 0
THEN
SELECT * FROM transactions_filtered
ELSE
SELECT * FROM transactions
但它沒有用。有沒有辦法僅基于引數條件來執行 UNION 特定表?
謝謝!
uj5u.com熱心網友回復:
將條件放在WHERE聯合查詢的子句中。
它是一個等價的變數,where 1=1它總是評估true以選擇所有行,where 1=2并且始終評估false以防止選擇任何行
set @paramfiltered := 1
SELECT * FROM main
UNION ALL
SELECT * FROM transactions_filtered WHERE @paramfiltered > 0
UNION ALL
SELECT * FROM transactions WHERE @paramfiltered <= 0
這是一個 sql 小提琴http://sqlfiddle.com/#!9/e6bba3/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516989.html
