Reputation: 73
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
Upvotes: 2
Views: 1746
Reputation: 6450
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.
Upvotes: 2
Reputation: 1153
I think like Brian :
You can try the "explain" command on your queries to see the plan the engine is using.
Upvotes: 2