[英]How to conditionally disable a join in SQL?
甲骨文,特别是。 我需要在声明性查询中的 SQL 中执行以下操作,而无需定义变量或 if 条件。 考虑以下 SQL:
SELECT *
FROM table1
JOIN table2 on table2.a = table1.a
WHERE table1.d = 4
AND c = (select c from table3 where b=3);
问题是,如果 table3 中没有匹配项,那么 table3 条件不应该适用而不是 table3 限制行(实际上只是删除了上述查询的最后一行)
如何在不先定义变量的情况下在单个 SQL 语句中执行此操作?
您可以添加NOT EXISTS
子句以有效删除c = ...
条件:
SELECT *
FROM table1
JOIN table2 on table2.a = table1.a
WHERE table1.d = 4
AND (NOT EXISTS (SELECT c FROM table3 WHERE b=3)
OR c = (SELECT c FROM table3 WHERE b=3)
)
子查询最多返回一个值。 您可以通过以下两种方式处理此问题,而无需额外的子查询:
c = all (select t3.c from table3 t3 where t3.b = 3)
这是有效的,因为all
匹配到一个空列表。
c = (select coalesce(max(t3.c), ?.c) from table3 t3 where t3.b = 3)
?
用于外部表参考。 这是有效的,因为如果没有匹配项, max()
将返回null
。 然后coalesce()
用匹配值替换该值。 注意:这假设外部c
不为null
。
您可能需要考虑在包含 col c 的表上使用左连接,如下所示
SELECT *
FROM table1
JOIN table2
on table2.a = table1.a
LEFT JOIN (select distinct c
from table3
where b=3
)tbl_3
ON table1.c=tbl_3.c /*i assumed that the column c is in table1*/
WHERE table1.d = 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.