[英]Query Optimization CASE vs UNION
This query returns records of user's friend from friendlist table and then get records of each user from user table. 该查询从friendlist表中返回用户朋友的记录,然后从user表中获取每个用户的记录。
OPTION # 1 选项1
SELECT
f.status,
f.user_to_id,
f.user_from_id,
u.user_id,
u.registration_date,
u.nickname,
u.email
FROM ti_friend_list AS f
LEFT JOIN ti_user u
ON u.user_id = (CASE f.user_from_id
WHEN 7 THEN f.user_to_id
ELSE f.user_from_id END)
WHERE (f.user_from_id = 7
OR f.user_to_id = 7)
OPTION # 2 选项#2
SELECT
f.status,
f.user_to_id,
f.user_from_id,
u.user_id,
u.registration_date,
u.nickname,
u.email
FROM ti_friend_list AS f
LEFT JOIN ti_user u
ON u.user_id = f.user_to_id
WHERE f.user_from_id = 7
UNION ALL
SELECT
f.status,
f.user_to_id,
f.user_from_id,
u.user_id,
u.registration_date,
u.nickname,
u.email
FROM ti_friend_list AS f
LEFT JOIN ti_user u
ON u.user_id = f.user_from_id
WHERE f.user_to_id = 7
Which One is more optimal solution. 哪一个是最佳解决方案。 Basically a comparison between CASE and UNION 基本上是CASE和UNION之间的比较
Run them both and see if there's a time difference! 同时运行它们,看看是否存在时差!
That aside, I would suggest use of the CASE approach is a clearer one in terms of the intention and ease of extension in the future, and I would use that unless you find clear evidence it's not performing. 除此之外,就将来的意图和扩展的方便性而言,我建议使用CASE方法是一种更清晰的方法,除非您有明确的证据表明它没有奏效,否则我会使用CASE方法。 Off the top of my head I think it would be faster though. 不过,我认为这会更快。
I think like Brian : 我认为像Brian一样:
You can try the "explain" command on your queries to see the plan the engine is using. 您可以在查询中尝试使用“解释”命令来查看引擎正在使用的计划。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.