Cyb*_*die 5 mysql sql 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 )
)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么COALESCE要以这种方式使用它:
COALESCE(:userAlternateId,null) is null
这是性能黑客还是它使查询数据库独立还是......?
顺便说一句userAlternateId,是字符串/varchar,其他 id 是长整型和from-to日期
我想不出以这种方式使用 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)
Run Code Online (Sandbox Code Playgroud)