1. 程式人生 > >mysql in 子查詢 效率慢 優化(轉)

mysql in 子查詢 效率慢 優化(轉)

現在的CMS系統、部落格系統、BBS等都喜歡使用標籤tag作交叉連結,因此我也嚐鮮用了下。但用了後發現我想查詢某個tag的文章列表時速度很慢,達到5秒之久!百思不解(後來終於解決),我的表結構是下面這樣的,文章只有690篇。

文章表article(id,title,content)
標籤表tag(tid,tag_name)
標籤文章中間表article_tag(id,tag_id,article_id)
其中有個標籤的tid是135,我幫查詢標籤tid是135的文章列表
用以下語句時發現速度好慢,我文章才690篇
select id,title from article where id in(
select article_id from article_tag where tag_id=135
)
其中這條速度很快:select article_id from article_tag where tag_id=135
查詢結果是五篇文章,id為428,429,430,431,432
我用寫死的方式用下面sql來查文章也很快
select id,title from article where id in(
428,429,430,431,432
)
我在SqlServer中好像不會這樣慢,不知MySQL怎樣寫好點,也想不出慢在哪裡。

後來我找到了解決方法:

select id,title from article where id in(
select article_id from (select article_id from article_tag where tag_id=135) as tbt
)

其它解決方法:(舉例)

mysql> select * from abc_number_prop where number_id in (select number_id from abc_number_phone where phone = '82306839');

為了節省篇幅,省略了輸出內容,下同。

67 rows in set (12.00 sec)

只有67行資料返回,卻花了12秒,而系統中可能同時會有很多這樣的查詢,系統肯定扛不住。用desc看一下(注:explain也可)

mysql> desc select * from abc_number_prop where number_id in (select number_id from abc_number_phone where phone = '82306839');
+----+--------------------+------------------+--------+-----------------+-------+---------+------------+---------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------------+--------+-----------------+-------+---------+------------+---------+--------------------------+
| 1 | PRIMARY | abc_number_prop | ALL | NULL | NULL | NULL | NULL | 2679838

| Using where |
| 2 | DEPENDENT SUBQUERY | abc_number_phone | eq_ref | phone,number_id | phone | 70 | const,func | 1 | Using where; Using index |
+----+--------------------+------------------+--------+-----------------+-------+---------+------------+---------+--------------------------+
2 rows in set (0.00 sec)

從上面的資訊可以看出,在執行此查詢時會掃描兩百多萬行,難道是沒有建立索引嗎,看一下

mysql>show index from abc_number_phone;
+------------------+------------+-------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------------+------------+-------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| abc_number_phone | 0 | PRIMARY | 1 | number_phone_id | A | 36879 | NULL | NULL | | BTREE | | |
| abc_number_phone | 0 | phone | 1 | phone | A | 36879 | NULL | NULL | | BTREE | | |
| abc_number_phone | 0 | phone | 2 | number_id | A | 36879 | NULL | NULL | | BTREE | | |
| abc_number_phone | 1 | number_id | 1 | number_id | A | 36879 | NULL | NULL | | BTREE | | |

| abc_number_phone | 1 | created_by | 1 | created_by | A | 36879 | NULL | NULL | | BTREE | | |
| abc_number_phone | 1 | modified_by | 1 | modified_by | A | 36879 | NULL | NULL | YES | BTREE | | |
+------------------+------------+-------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
6 rows in set (0.06 sec)

mysql>show index from abc_number_prop;
+-----------------+------------+-------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-----------------+------------+-------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| abc_number_prop | 0 | PRIMARY | 1 | number_prop_id | A | 311268 | NULL | NULL | | BTREE | | |
| abc_number_prop | 1 | number_id | 1 | number_id | A | 311268 | NULL | NULL | | BTREE | | |

| abc_number_prop | 1 | created_by | 1 | created_by | A | 311268 | NULL | NULL | | BTREE | | |
| abc_number_prop | 1 | modified_by | 1 | modified_by | A | 311268 | NULL | NULL | YES | BTREE | | |
+-----------------+------------+-------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
4 rows in set (0.15 sec)

從上面的輸出可以看出,這兩張表在number_id欄位上建立了索引的。

看看子查詢本身有沒有問題。

mysql> desc select number_id from abc_number_phone where phone = '82306839';
+----+-------------+------------------+------+---------------+-------+---------+-------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+------+---------------+-------+---------+-------+------+--------------------------+
| 1 | SIMPLE | abc_number_phone | ref | phone | phone | 66 | const | 6 | Using where; Using index |
+----+-------------+------------------+------+---------------+-------+---------+-------+------+--------------------------+
1 row in set (0.00 sec)

沒有問題,只需要掃描幾行資料,索引起作用了。查詢出來看看

mysql> select number_id from abc_number_phone where phone = '82306839';
+-----------+
| number_id |
+-----------+
| 8585 |
| 10720 |
| 148644 |
| 151307 |
| 170691 |
| 221897 |
+-----------+
6 rows in set (0.00 sec)

直接把子查詢得到的資料放到上面的查詢中

mysql> select * from abc_number_prop where number_id in (8585, 10720, 148644, 151307, 170691, 221897);

67 rows in set (0.03 sec)

速度也快,看來MySQL在處理子查詢的時候是不夠好。我在MySQL 5.1.42 和 MySQL 5.5.19 都進行了嘗試,都有這個問題。

搜尋了一下網路,發現很多人都遇到過這個問題:

參考資料1:使用連線(JOIN)來代替子查詢(Sub-Queries) mysql優化系列記錄
http://blog.csdn.net/hongsejiaozhu/article/details/1876181
參考資料2:網站開發日記(14)-MYSQL子查詢和巢狀查詢優化
http://dodomail.iteye.com/blog/250199

根據網上這些資料的建議,改用join來試試。

修改前:select * from abc_number_prop where number_id in (select number_id from abc_number_phone where phone = '82306839');

修改後:select a.* from abc_number_prop a inner join abc_number_phone b on a.number_id = b.number_id where phone = '82306839';

mysql> select a.* from abc_number_prop a inner join abc_number_phone b on a.number_id = b.number_id where phone = '82306839';

67 rows in set (0.00 sec)

效果不錯,查詢所用時間幾乎為0。看一下MySQL是怎麼執行這個查詢的

mysql>desc select a.* from abc_number_prop a inner join abc_number_phone b on a.number_id = b.number_id where phone = '82306839';
+----+-------------+-------+------+-----------------+-----------+---------+-----------------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+-----------------+-----------+---------+-----------------+------+--------------------------+
| 1 | SIMPLE | b | ref | phone,number_id | phone | 66 | const | 6 | Using where; Using index |
| 1 | SIMPLE | a | ref | number_id | number_id | 4 | eap.b.number_id | 3 | |
+----+-------------+-------+------+-----------------+-----------+---------+-----------------+------+--------------------------+
2 rows in set (0.00 sec)

小結:當子查詢速度慢時,可用JOIN來改寫一下該查詢來進行優化。

網上也有文章說,使用JOIN語句的查詢不一定總比使用子查詢的語句快。

mysql手冊也提到過,具體的原文在mysql文件的這個章節:

I.3. Restrictions on Subqueries

13.2.8. Subquery Syntax

摘抄:

1)關於使用IN的子查詢:

Subquery optimization for IN is not as effective as for the = operator or for IN(value_list) constructs.

A typical case for poor IN subquery performance is when the subquery returns a small number of rows but the outer query returns a large number of rows to be compared to the subquery result.

The problem is that, for a statement that uses an IN subquery, the optimizer rewrites it as a correlated subquery. Consider the following statement that uses an uncorrelated subquery:

SELECT ... FROM t1 WHERE t1.a IN (SELECT b FROM t2);

The optimizer rewrites the statement to a correlated subquery:

SELECT ... FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.b = t1.a);

If the inner and outer queries return M and N rows, respectively, the execution time becomes on the order of O(M×N), rather than O(M+N) as it would be for an uncorrelated subquery.

An implication is that an IN subquery can be much slower than a query written using an IN(value_list) construct that lists the same values that the subquery would return.

2)關於把子查詢轉換成join的:

The optimizer is more mature for joins than for subqueries, so in many cases a statement that uses a subquery can be executed more efficiently if you rewrite it as a join.

An exception occurs for the case where an IN subquery can be rewritten as a SELECT DISTINCT join. Example:

SELECT col FROM t1 WHERE id_col IN (SELECT id_col2 FROM t2 WHERE condition);

That statement can be rewritten as follows:

SELECT DISTINCT col FROM t1, t2 WHERE t1.id_col = t2.id_col AND condition;

But in this case, the join requires an extra DISTINCT operation and is not more efficient than the subquery

相關推薦

mysql in 查詢 效率 優化

現在的CMS系統、部落格系統、BBS等都喜歡使用標籤tag作交叉連結,因此我也嚐鮮用了下。但用了後發現我想查詢某個tag的文章列表時速度很慢,達到5秒之久!百思不解(後來終於解決),我的表結構是下面這樣的,文章只有690篇。 文章表article(id,title,content) 標籤表tag(tid,

MySQL索引原理及查詢優化

範圍 很難 等於 right 事件 原理 插入 jpg 個人網站 轉自:美團點評技術團隊http://tech.meituan.com/mysql-index.html MySQL憑借著出色的性能、低廉的成本、豐富的資源,已經成為絕大多數互聯網公司的首選關系型數據庫。雖然性

眼睜睜地踩到 MySQL in 查詢的“坑”

前言 MySQL是專案中常用的資料庫,其中in查詢也是很常用。最近專案除錯過程中,遇到一個出乎意料的select查詢,竟然用了33秒! 一、表結構 1. userinfo 表 2. article 表 二、問題SQL例項 select*fromuserinfowhereidin(selectau

MySQL IN查詢

近日通過《mysql技術內幕:SQL程式設計》學習mysql子查詢,書中介紹了IN子查詢存在的問題,並且提供了一些優化方法。我在此書的基礎上進行了深入研究,總結幾點。 MySql優化器對IN子查詢優化時存在一個問題,MySql優化器對於IN語句的優化是“LAZY”的。對於I

Mysql數據庫性能優化

效率 dir sort variables 緩存 模型 mysql5.6 包含 dpt 參考 http://www.jb51.net/article/82254.htm 今天,數據庫的操作越來越成為整個應用的性能瓶頸了,這點對於Web應用尤其明顯。關於數據庫的性能,這並不只

Mysql優化

進行 模式 系統 b樹 stat 內存 很多 提高 優化mysql Mysql優化主要通過執行計劃,索引,sql語句,調整mysql內部配置 (http://blog.chinaunix.net/uid-11640640-id-3426908.html) 一、優化概述

sqlserver2008查詢性能優化文摘

TP ron 性能 分析 bubuko inf tro str sqlserve 第1章 sql查詢性能調整 第4章 索引分析 sqlserver2008查詢性能優化(文摘)

mysql性能優化之索引優化

形式 字符串類 b樹索引 基礎 var 開發 null -- mysql服務器 作為免費又高效的數據庫,mysql基本是首選。良好的安全連接,自帶查詢解析、sql語句優化,使用讀寫鎖(細化到行)、事物隔離和多版本並發控制提高並發,完備的事務日誌記錄,強大的存儲引擎提供高效查

MySQL Bug#67718淺談B+樹索引的分裂優化

原文連結:http://hedengcheng.com/?p=525   問題背景 今天,看到Twitter的DBA團隊釋出了其最新的MySQL分支:Changes in Twitter MySQL 5.5.28.t9,此分支最重要的一個改進,就是修復了MySQL 的Bug #67718:In

mysql中分組查詢和分組篩選講義

----分組查詢&篩選學習: --關鍵字:group by 分組欄位名,分組欄位名.... --注意1:使用了分組後,在select語句中只允許出現分組欄位和多行函式。 --注意2:如果是多欄位分組,則先按照第一欄位分組,

Oracle 查詢技巧與優化 多表查詢

前言 上一篇blog介紹了Oracle中的單表查詢和排序的相關技巧(http://blog.csdn.net/wlwlwlwl015/article/details/52083588),本篇blog繼續介紹查詢中用的最多的——多表查詢的技巧與優化方式,下面依舊

MySql之ALTER命令用法詳細解讀

修改表 pre const 命令使用 add ear 修改 blog rain 本文詳細解讀了MySql語法中Alter命令的用法,這是一個用法比較多的語法,而且功能還是很強大的。 USE learning;(自己要提前建好) CREATE TABLE student

頁面重繪和回流以及優化

圖片大小 處理流 create 意圖 borde 基本上 nal arch 似的 源文章地址:http://www.css88.com/archives/4996 在討論頁面重繪、回流之前。需要對頁面的呈現流程有些了解,頁面是怎麽把html結合css等顯示到瀏覽器上的,下面

從-View-繪制談性能優化

有趣 || left 例子 bject create 我想 roo 並且 在開發過程中,往往會聽到 “性能優化” 這個概念,這個概念很大,比如網絡性能優化、耗電量優化等等,對我們開發者而言,最容易做的,或者是影響最大的,應該是 View 的性能優化。一般小項目或許用不上

PostgreSQL CPU滿(100%)性能分析及優化

mark ike -- 過多 mar 是不是 影響 sas sql日誌 PostgreSQL CPU滿(100%)性能分析及優化 轉自:https://help.aliyun.com/knowledge_detail/43562.html 在數據庫運維當中,

10種簡單的Java性能優化

IT none hset 工作流程 執行 為什麽 util 服務器 也有 本文由 ImportNew - 一直在路上 翻譯自 jaxenter。歡迎加入翻譯小組。轉載請見文末要求。你是否正打算優化hashCode()方法?是否想要繞開正則表達

mysql狀態分析之show global status

http 運行 global 系統性能 數據量 -- ror 必須 request mysql> show global status;可以列出MySQL服務器運行各種狀態值,我個人較喜歡的用法是show status like ‘查詢值%‘;一、慢查詢mysql&g

php網站速度效能優化

一個網站的訪問開啟速度至關重要,特別是首頁的開啟載入過慢是致命性的,本文介紹關於php網站效能優化方面的實戰案例:淘寶首頁載入速度優化實踐 。想必很多人都已經看到了新版的淘寶首頁,它與以往不太一樣,這一版頁面中四處彌散著個性化的味道,由於獨特的個性化需求,前端也面臨各方面的技術挑戰:  

處理百萬級以上的資料提高查詢速度的方法

處理百萬級以上的資料提高查詢速度的方法:  1.應儘量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描。  2.對查詢進行優化,應儘量避免全表掃描,首先應考慮在 where 及 order by 涉及的列上建立索引。  3.應儘

關於Eclipse的一些設定和優化

1.關閉 Updating index 2.讓Eclipse啟動時只加載所需專案(去掉右側不需要的專案的勾選) 3.設定jsp檔案預設開啟方式(其它型別檔案設定方法相同) 4.修改jsp頁面預設編碼格式 5.讓新建Java時添加個性註釋