[英]CASE or COALESCE performance in WHERE clause for MySQL
I'm wondering which is the better performance or best practice when dealing with multiple criteria in the WHERE clause and NULL values. 我想知道在WHERE子句和NULL值中处理多个条件时哪个是更好的性能或最佳实践。
WHERE
u.id = COALESCE(user_id, u.id) AND
su.custom_id = COALESCE(student_number, su.custom_id)
OR 要么
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
I would avoid both of those approaches. 我会避免这两种方法。 You should be able to accomplish what you are trying to do with a judicious use of AND
, OR
, IS NULL
, and parentheses. 你应该能够通过明智地使用AND
, OR
, IS NULL
和括号来完成你想要做的事情。
For example, you can rewrite this: 例如,您可以重写:
WHERE
u.id = COALESCE(user_id, u.id) AND
su.custom_id = COALESCE(student_number, su.custom_id)
Like this: 像这样:
WHERE
(user_id IS NULL OR u.id = user_id) AND
(su.custom_id = student_number)
And you can rewrite this: 你可以改写这个:
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
As this: 这样:
WHERE
(user_id IS NOT NULL AND LENGTH(user_id) > 0 AND u.id = user_id)
OR
(su.custom_id = student_number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.