關於Mysql left join和子查詢

2021-08-28 07:50:55 字數 937 閱讀 9087

背景:

今天在做乙個專案的時候需要關聯查詢,但是好奇想知道left join 和子查詢哪乙個比較合適。

於是做了個實驗。

子查詢:

select a.*,(select content from yxhy_news_content  where

yxhy_news_content.id=a.id) as content from `yxhy_news` `a` where  `a`.`id` = '47'

limit 1    

查詢時間為0.735

left join查詢

select * from yxhy_news a left join yxhy_news_content b on b.id=a.id where a.id=47;

查詢時間為0.188s

很明顯,left join 要比子查詢效率高。其原因是子表的id是沒有新增索引的。

在yxhy_news_content這個子表新增主鍵索引後實驗結果如下。

left join查詢結果:

select * from yxhy_news a left join yxhy_news_content b on b.id=a.id where a.id=61

時間為:0.055s

子查詢結果:

select a.*,(select content from yxhy_news_content  where 

yxhy_news_content.id=a.id) as content from `yxhy_news` `a` where  `a`.`id` = 61 

limit 1

很明顯子查詢效果要比left join效率要高,但是還是不建議在from之前使用子查詢。即使是有主鍵的情況下也不要這麼使用。

100萬資料表未建索引的情況下,連線會比用子查詢快幾倍,建索引後兩種查詢效能差不多。

MySQL left join 避坑指南

這裡我先給出乙個場景,並丟擲兩個問題,如果你都能答對那這篇文章就不用看了。那麼現在有兩個需求 找出每個班級的名稱及其對應的女同學數量 找出一班的同學總數 對於需求1,大多數人不假思索就能想出如下兩種sql寫法 正確 select c.name,count s.name as num from cla...

MYSQl left join聯合查詢效率分析

user表 id name 1 libk 2 zyfon 3 daodao user action表 user id action 1 jump 1 kick 1 jump 2 run 4 swim sql select id,name,action from user as u left join...

MYSQl left join 聯合查詢效率分析

user表 id name 1 libk 2 zyfon 3 daodao user action表 user id action 1 jump 1 kick 1 jump 2 run 4 swim sql select id,name,action from user as u left join...