2013-07-25 44 views
4

我有兩個表:爲什麼在使用JOIN而不是WHERE時MySQL很慢?

CREATE TABLE `test_sample` (
    `idtest_sample` varchar(50) NOT NULL, 
    `test_samplecol` varchar(45) DEFAULT NULL, 
    UNIQUE KEY `idtest_sample_UNIQUE` (`idtest_sample`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 

CREATE TABLE `new_table` (
    `idnew_table` int(11) NOT NULL, 
    UNIQUE KEY `idnew_table_UNIQUE` (`idnew_table`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 

第一個表中包含500萬條記錄,而第二個只有10條記錄。

這個查詢的執行的持續時間是5秒以上:

SELECT * FROM test_sample 
INNER JOIN new_table 
ON test_sample.idtest_sample = new_table.idnew_table 

在執行該查詢立即(小於0.001秒):

SELECT * FROM test_sample 
WHERE test_sample.idtest_sample IN 
('3','1597','25963','170596','196485', 
'545963','999999','1265896','1569485','1999999') 

爲什麼第一查詢需要太長?

+0

如果您嘗試'SELECT test_sample。* FROM ...'您的第一個查詢,該怎麼辦? – fthiella

+0

對這兩個查詢運行[EXPLAIN](http://dev.mysql.com/doc/refman/5.0/en/explain.html)。 –

+0

即使第二張表具有良好的索引? –

回答

2

您是否嘗試查看執行路徑? DESC {SQL},您的第一個查詢肯定會更長

第一個查詢肯定會查看另一個表中每行的整個5百萬行。 當你的第二個查詢僅尋找具有索引特定ID(因爲他們是主鍵的一部分)

編輯: 這裏有您詳解(簡體):

+----+-------------+-------------+--------+----------------------+------+ 
| id | select_type | table  | type | possible_keys  | key | 
+----+-------------+-------------+--------+----------------------+------+ 
| 1 | SIMPLE  | new_table | system | idnew_table_UNIQUE | NULL | 
| 1 | SIMPLE  | test_sample | ALL | idtest_sample_UNIQUE | NULL | 
+----+-------------+-------------+--------+----------------------+------+ 
+----+-------------+-------------+-------+----------------------+----------------------+ 
| id | select_type | table  | type | possible_keys  | key     | 
+----+-------------+-------------+-------+----------------------+----------------------+ 
| 1 | SIMPLE  | test_sample | const | idtest_sample_UNIQUE | idtest_sample_UNIQUE | 
+----+-------------+-------------+-------+----------------------+----------------------+ 

正如你所看到的有一個在test_sample表「全部」掃描(5個百萬行)

你可能想看看這裏:http://hackmysql.com/case4

+0

那麼,是否有可能在MySQL中使用JOIN,它不會查看整個表格,而只能查看特定的ID? – Panayotis

1

第一個查詢將需要更多的時間,因爲它檢查另一個TA的每一行500萬條記錄。另一方面第二個sql有一定的索引列。 希望它能幫助你。

相關問題