简体   繁体   English

查询优化CASE与UNION

[英]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一样:

  • I think it is more difficult for the engine to optimize a UNION because you can unifiate very different things ! 我认为引擎优化UNION更加困难,因为您可以统一非常不同的东西!
  • The problem with UNION is that you must repeat the SELECT part of the query and don't make mistakes UNION的问题在于,您必须重复查询的SELECT部分​​,并且不要出错
  • The engine will perform the first part of the union, then the second part and then combine. 引擎将执行并集的第一部分,然后执行第二部分,然后合并。 I think some of the steps will be done twice. 我认为某些步骤将执行两次。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM