简体   繁体   English

SELECT 子查询值上的 SQL 条件

[英]SQL Conditional on SELECT Subquery value

I want to apply a condition check on my select subquery.我想对我的选择子查询应用条件检查。 How can I do it optimally?我怎样才能做到最好?

Here's the initial query:这是初始查询:

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

And I want to add the WHERE condition subResult = :parameter .我想添加 WHERE 条件subResult = :parameter And the :parameter is optional, meaning if :parameter is null, include row in result.并且:parameter是可选的,这意味着如果:parameter为空,则在结果中包含行。

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

But I can't reference the result of the subquery subResult inside my WHERE condition.但是我无法在 WHERE 条件中引用子查询subResult的结果。

I can copy/paste the subquery into the WHERE clause, but that seems sloppy and error prone:我可以将子查询复制/粘贴到 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)

If you are running Oracle 12 or higher, I would recommend a lateral join:如果您运行的是 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)

In earlier versions, you can use a subquery or CTE:在早期版本中,您可以使用子查询或 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)
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM