简体   繁体   English

为什么在sql语句中使用COALESCE()?

[英]Why use COALESCE() in sql statement?

I'm refactoring some old code and stumbled upon this named query (It's using hibernate on top of mysql): 我正在重构一些旧代码并偶然发现这个命名查询(它在mysql之上使用hibernate):

delete F from
    foo F
inner join user DU on F.user_id = DU.id
where
(COALESCE(:userAlternateId,null) is null or DU.alternate_id like :userAlternateId )
    and ( COALESCE(:fooId,null) is null or F.foo_id like :fooId )
    and (
        ( COALESCE(:fromUpdated,null) is null or F.updated_at>=:fromUpdated )
        and ( COALESCE(:toUpdated,null) is null or F.updated_at<=:toUpdated )
)

I don't understand why this COALESCE is being used in this fashion: COALESCE(:userAlternateId,null) is null 我不明白为什么这个COALESCE以这种方式使用: COALESCE(:userAlternateId,null) is null

Is this a performance hack or does it make the query database independent or ...? 这是性能破解还是使查询数据库独立或......?

btw userAlternateId is a string/varchar, other id's are longs and from-to are dates btw userAlternateId是一个字符串/ varchar,其他id是long, from-to是日期

I can't think of any reason for COALESCE being used this way. 我想不出COALESCE以这种方式使用的任何理由。

Following statement is equivalent 以下陈述是等效的

DELETE  F 
FROM    foo F
        INNER JOIN User DU on F.user_id = DU.id
WHERE   (:userAlternateId IS NULL OR DU.alternate_id LIKE :userAlternateId)
        AND (:fooId IS NULL OR F.foo_id LIKE :fooId)
        AND (:fromUpdated IS NULL OR F.updated_at >= :fromUpdated)
        AND (:toUpdated IS NULL OR F.updated_at <= :toUpdated)

Yep, thinking about this more, I'm betting on what I suggested in the comment on the question. 是的,考虑到这一点,我打赌我在问题评论中建议的内容。 Either it's auto-generated code, and its an artefact of the way the code generating that code has to handle more general issues than the particular case it's dealing with here, or it's an artefact of someone moving from something more reasonable like COALESCE(:userAlternateId, "not set") = "not set" to COALESCE(:userAlternateId,null) is null , which while not very sensible, is something that you can see how someone could get from A to B. 要么它是自动生成的代码,要么是生成代码的代码必须处理比它在这里处理的特定情况更常见的问题的方式,或者它是某人从更合理的东西COALESCE(:userAlternateId, "not set") = "not set"COALESCE(:userAlternateId, "not set") = "not set"转移的人工制品COALESCE(:userAlternateId, "not set") = "not set"COALESCE(:userAlternateId,null) is null ,虽然不是很明智,但您可以看到某人如何从A到B.

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

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