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

时间:2010-09-30 11:19:11

标签: sql mysql coalesce

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

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

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

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

是的,考虑到这一点,我打赌我在评论中提出的建议。要么它是自动生成的代码,要么是生成代码的代码必须处理比它在这里处理的特定情况更常见问题的方式,或者它是某人从更合理的事情中移动的人工制品,如{{1} } COALESCE(:userAlternateId, "not set") = "not set",虽然不是很明智,但你可以看到某人如何从A到B。

相关问题