我有兩個MySQL表與後續的結構:如何優化此查詢?
mysql> describe symbol;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| symbol | varchar(250) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> describe price;
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| id_symbol | int(11) | NO | MUL | NULL | |
| date | date | NO | MUL | NULL | |
| price | double | NO | | NULL | |
+-----------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
我要查詢價格表來獲得與兩個符號N個價格清單(對它們進行比較)
這是一個樣品結果:
DATE SYMBOL 1 SYMBOL 2
2011-01-01 100 23
2011-01-02 92 26
2011-01-03 89 50
所以我需要找到兩個相同的數據並返回他們的價格。 我已經創建了一個看起來可以完成這項工作的查詢,但可能並不是非常優化。
SELECT *
FROM price AS a
JOIN price AS b ON a.date = b.date
WHERE a.id_symbol = 1 AND b.id_symbol = 2
ORDER BY a.date DESC
LIMIT 100
您怎麼看?
我可以優化查詢做些什麼(或者可以改變表結構)嗎?
編輯:
這是EXPLAIN {查詢}的
mysql> EXPLAIN SELECT *
-> FROM price AS a
-> JOIN price AS b ON a.date = b.date
-> WHERE a.id_symbol = 1 AND b.id_symbol = 2
-> ORDER BY a.date DESC
-> LIMIT 100;
+----+-------------+-------+------+----------------+-----------+---------+-------+------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------+-----------+---------+-------+------+-----------------------------+
| 1 | SIMPLE | a | ref | date,id_symbol | id_symbol | 4 | const | 921 | Using where; Using filesort |
| 1 | SIMPLE | b | ref | date,id_symbol | id_symbol | 4 | const | 966 | Using where |
+----+-------------+-------+------+----------------+-----------+---------+-------+------+-----------------------------+
2 rows in set (0.03 sec)
你認爲什麼結果呢?
然後......什麼是解釋「行」列中的921和966?如果我數 價格我有符號1和符號2我得到:912和912: - | 是什麼?
(PS是的,我的錯誤,我不得不改變*與我想要的列)
「不是非常優化」?有什麼問題? – Vache
您的查詢是否緩慢? – Ibu
你不想指定不使用'select *'的列嗎? – Rup