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

问题描述 投票:4回答:2

我正在重构一些旧代码并偶然发现这个命名查询(它在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 )
)

我不明白为什么这个COALESCE以这种方式使用:COALESCE(:userAlternateId,null) is null

这是性能破解还是使查询数据库独立或......?

btw userAlternateId是一个字符串/ varchar,其他id是long,from-to是日期

sql mysql coalesce
2个回答
2
投票

我想不出COALESCE以这种方式使用的任何理由。

以下陈述是等效的

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)

2
投票

是的,考虑到这一点,我打赌我在问题评论中建议的内容。无论是自动生成的代码,还是生成代码的代码处理比一般处理问题的方式更常见的问题,或者是某人从COALESCE(:userAlternateId, "not set") = "not set"更合理的东西转移到COALESCE(:userAlternateId,null) is null的人工制品,虽然不是很明智,但你可以看到有人可以从A到B.

© www.soinside.com 2019 - 2024. All rights reserved.