我想知道在WHERE子句和NULL值中处理多个条件时哪个是更好的性能或最佳实践.
WHERE
u.id = COALESCE(user_id,u.id) AND
su.custom_id = COALESCE(student_number,su.custom_id)
要么
WHERE
CASE
WHEN user_id IS NOT NULL AND LENGTH(user_id) > 0
THEN
u.id = user_id
ELSE
su.custom_id = student_number
END
最佳答案
我会避免这两种方法.你应该能够通过明智地使用AND,OR,IS NULL和括号来完成你想要做的事情.
原文链接:https://www.f2er.com/mysql/433636.html例如,您可以重写:
WHERE
u.id = COALESCE(user_id,su.custom_id)
像这样:
WHERE
(user_id IS NULL OR u.id = user_id) AND
(su.custom_id = student_number)
你可以改写这个:
WHERE
CASE
WHEN user_id IS NOT NULL AND LENGTH(user_id) > 0
THEN
u.id = user_id
ELSE
su.custom_id = student_number
END
这样:
WHERE
(user_id IS NOT NULL AND LENGTH(user_id) > 0 AND u.id = user_id)
OR
(su.custom_id = student_number)