【问题标题】:Case condition in hqlhql中的案例条件
【发布时间】:2020-07-06 14:54:21
【问题描述】:

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

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

【问题讨论】:

  • 但是 HQL 呢?我不能用吗?那么你将如何实现 if 语句
  • 我的意思是...人有名字,idMother 和 idFather,我只希望“idFather = :idFather”条件在没有 idMother 时工作,如果有 idMother,我不希望“父亲”条件起作用。
  • @SimonMartinelli CASE 可用于标准 SQL 的 WHERE 子句中。
  • 哦,你是对的。对不起
  • @Martinez 如果 idMother 不为空但不等于 :idMother 你想要基于 idFather 的连接吗?或者如果 idMother 为空,仅会使用 idFather?

标签: java sql hibernate hql


【解决方案1】:

这个查询:

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 匹配来加入。
如果这是不可能的,那么只有当idMother 是null 时,才会使用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)
  )
)

【讨论】:

  • 第二个是最近的,但我得到了 2 个寄存器,一个来自母亲条件,idMother 不为空,idFather 为,另一个来自 idFather,其中 idMother 为空,有什么办法可以只选择母寄存器?
  • 我不知道你说的2个寄存器是什么意思。在像Person 这样的表中,每一行必须通过 id 列或名称是唯一的。因此,在您设置的条件下,结果应该是唯一的行。返回 idMother 为 null 的 idFather 中的一个,因为这是您问题中的要求:始终执行“mother”条件,但如果没有mother,则执行“dad” " 有条件的
  • 查看我的 3d 查询。
  • 工作得很好,谢谢你的朋友,你能支持我的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 2011-10-25
相关资源
最近更新 更多