[英]optimize SQL query with multiple JOIN
如何優化此查詢並提高其性能,
SELECT user.id,user.name,profile.info,score.amount
FROM user
LEFT JOIN profile ON profile.user_id = user.id AND profile.type = 'language'
LEFT JOIN score ON score.user_id = user.id AND score.type = 'total'
WHERE email = 'example@mail.com'
返回結果:
[id] => 1060225
[name] => john
[info] => En
[ammount] => 533
返回結果2:
[id] => 1022805
[name] => karin
[info] =>
[ammount] => 11
表:
用戶表
id name email
1 john example@mail.com
2 karin tt@kkk.com
3 Tom kk@yahoo.com
4 kit mm@gmail.com
資料表
id user_id type info
1 1 is_admin true
2 1 language En
3 1 active true
4 2 is_admin false
1 1 like null
2 2 favorite null
3 3 is_admin false
4 2 experience 4
得分表
id user_id type amount
1 1 daily 33
2 1 total 533
3 2 total 11
4 3 daily 44
謝謝,
對於此查詢:
SELECT u.id, u.name, p.info, s.amount
FROM user u LEFT JOIN
profile p
ON p.user_id = u.id AND p.type = 'language' LEFT JOIN
score s
ON s.user_id = u.id AND s.type = 'total'
WHERE u.email = 'example@mail.com';
(我只是添加了表別名,以使查詢更具可讀性並闡明列的來源。)
嘗試以下索引:
create index idx_user_email_id_name on user(email, id, name);
create index idx_profile_userid_type on profile(user_id, type);
create index idx_score_userid_type on score(user_id, type);
您應該在(type, user_id)
上為profile
和score
表提供復合索引。 我不確定首先在索引中使用type
還是user_id
會更好,您應該嘗試使用它們中的每一個並查看哪個更好; 您可以使用EXPLAIN
對此執行計划進行比較。
您可以嘗試在連接列上創建索引(如果尚未創建索引),並使用子查詢代替連接:
SELECT
id,
name,
(select info from profile where user_id = user.id AND type = 'language') as "info",
(select amount from score where user_id = user.id and type = 'total') as "amount"
FROM user
WHERE email = 'example@mail.com'
其他技巧:檢查執行計划,添加索引以避免在適當情況下進行全表掃描,並在必要時通過復制某些數據或使用視圖來對表進行非規范化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.