简体   繁体   中英

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.

OPTION # 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

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

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. Off the top of my head I think it would be faster though.

I think like Brian :

  • I think it is more difficult for the engine to optimize a UNION because you can unifiate very different things !
  • The problem with UNION is that you must repeat the SELECT part of the query and don't make mistakes
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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