case条件

oo7oh9g9  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(416)

我试图用这个查询实现的是:总是做“母亲”条件,但是如果没有母亲,那么就做“父亲”条件,这可行吗?

"select name from Person where idParents = :idParents and"
                        + " CASE " + 
                        "       WHEN idMother !=NULL THEN idMother = :idMother " + 
                        "       ELSE idFather = :idFather " + 
                        "   END";
watbbzwu

watbbzwu1#

此查询:

select name 
from Person 
where idParents = :idParents 
and 1 = case
  when idMother = :idMother then 1
  when idFather = :iidFather then 1 
end

将首先通过匹配列来尝试联接 idMother:idMother .
如果这是不可能的,那么一个匹配的 idFather:idFather 将被使用,如果它存在的话。
此查询:

select name 
from Person 
where idParents = :idParents 
and 1 = case
  when idMother = :idMother then 1
  when idMother is null and idFather = :idFather then 1 
end

将首先通过匹配列来尝试联接 idMother:idMother .
如果这是不可能的,那么,只有 idMothernull ,匹配 idFather:idFather 将被使用,如果它存在的话。
或者你想要这个:

select p.name 
from Person p
where p.idParents = :idParents 
and (
  p.idMother = :idMother
  or (
    p.idFather = :idFather
    and not exists (select 1 from Person where idParents = p.idParents and idMother = :idMother)
  )
)

相关问题