假设我有这个问题:
SELECT a.id,
c.c_date
FROM table_a a
JOIN table_c c ON a.id = c.id
WHERE c_date is null;
我还有这个变量: p_filter
当此变量等于'yes'时,我希望先前显示的查询如图所示执行,以便表a和表c连接,并且搜索c_date的空值。如果变量等于'no'或任何其他值,我不想使用table_c而不加入,这样查询就会执行如下:
SELECT a.id
--omitted c.c_date
FROM table_a a ;
--omitted JOIN table_c c ON a.id = c.id
--omitted WHERE c_date is null;
答案 0 :(得分:0)
也许你可以试试这个;)
SELECT DISTINCT a.id,
CASE WHEN $p_filter = 'yes' THEN c.c_date ELSE NULL END AS c_date
FROM table_a a
JOIN table_c c ON $p_filter = 'no' OR (a.id = c.id AND c.c_date IS NULL);
已编辑:
SELECT DISTINCT a.id,
c.c_date
FROM table_a a
LEFT JOIN table_c c ON $p_filter = 'yes' AND a.id = c.id AND c.c_date IS NULL;
答案 1 :(得分:0)
SELECT a.id, c.c_date
FROM table_a a JOIN table_c c ON a.id = c.id
WHERE :p_filter = 'yes' AND c_date IS NULL
UNION ALL
SELECT a.id, NULL c_date
FROM table_a a
WHERE NVL (:p_filter, 'no') != 'yes'