SQL 以 SELECT 子查询值为条件

SQL Conditional on SELECT Subquery value

我想对我的 select 子查询应用条件检查。我怎样才能做到最好?

这是初始查询:

SELECT 
  table1.column1, 
  (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) as subResult
FROM table1
WHERE table1.column2 = "something"

我想添加 WHERE 条件 subResult = :parameter:parameter 是可选的,这意味着如果 :parameter 为空,则在结果中包含行。

WHERE table1.column2 = "something" AND (:parameter is null or subResult = :parameter)

但是我无法在我的 WHERE 条件中引用子查询 subResult 的结果。

我可以 copy/paste 将子查询放入 WHERE 子句中,但这看起来草率且容易出错:

SELECT 
  table1.column1, 
  (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) as subResult
FROM table1
WHERE table1.column2 = "something" AND (:parameter is null or (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) = :parameter)
select * 
from  (SELECT 
         table1.column1, 
        (SELECT min(table2.column1) FROM table2 WHERE table2.table1Id = table1.id) as  subResult
    FROM table1
    WHERE table1.column2 = "something"
    )
where   subResult = decode(:p,null , subResult ,:p)

如果您是 运行 Oracle 12 或更高版本,我建议使用横向连接:

select t1.column1, t2.min_column1
from table1 t1
outer apply (select min(t2.column1) min_column1 from table2 t2 where t2.table1id = t1.id) t2
where 
    t1.column2 = 'something' 
    and (:parameter is null or t2.min_column1 = :parameter)

在早期版本中,您可以使用子查询或 CTE:

select *
from (
    select t1.column1, 
        (select min(t2.column1) from table2 t2 where t2.table1id = t1.id) as min_column1
    from table1 t1
) t
where 
    t1.column2 = 'something' 
    and (:parameter is null or t2.min_column1 = :parameter)