我有兩個表。在該表中UnRevisedTable而來的原始數據,並在表RevisedTable有哪些,當他發現在UnRevisedTable比他不喜歡的值人類插入修正值的唯一入口。從兩個表查詢:消耗時間
在UnRevisedTable有每分鐘一個條目和RevisedTable沒有在UnRevisedTable每一個不必要的侵入一個條目。
這兩個查詢的目的是相同的:當修改數據時,請告訴我修改數據和無修改數據的聯合,替換未修改數據。
我開始編寫query2,但速度太慢。然後我寫了query1,而且query1要快得多。
我的問題是爲什麼query1比query2快?謝謝。
query1:
SELECT o.start_date_time,
CASE WHEN r.start_date_time IS NULL THEN o.value ELSE r.value END AS value,
FROM UnRevisedTable o LEFT JOIN RevisedTable r ON o.start_date_time = r.start_date_time
WHERE o.start_date_time >= '".$start."' AND o.start_date_time < '".$finish."' ORDER BY start_date_time ASC;
query2:
select * from(
select RevisedTable.* from RevisedTable where start_date_time between '".$start."' and '".$finish."'
union
select UnRevisedTable.* from UnRevisedTable where start_date_time between '".$start."' and '".$finish."'
) as t1 group by start_date_time;
由於Abhik Chakraborty sugested這裏的解釋QUERY1並解釋QUERY2:
QUERY1:
+----+-------------+-------+--------+---------------+---------+---------+------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+------------------------+------+-------------+
| 1 | SIMPLE | o | range | PRIMARY | PRIMARY | 8 | NULL | 9 | Using where |
| 1 | SIMPLE | r | eq_ref | PRIMARY | PRIMARY | 8 | Mydb.o.start_date_time | 1 | |
+----+-------------+-------+--------+---------------+---------+---------+------------------------+------+-------------+
QUERY2:
+----+--------------+------------+-------+---------------+---------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------+------------+-------+---------------+---------+---------+------+------+---------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 14 | Using temporary; Using filesort |
| 2 | DERIVED | RevisedTable | range | PRIMARY | PRIMARY | 8 | NULL | 2 | Using where |
| 3 | UNION | UnRevisedTable| range | PRIMARY | PRIMARY | 8 | NULL | 10 | Using where |
| NULL | UNION RESULT | <union2,3> | ALL | NULL | NULL | NULL | NULL | NULL | |
+----+--------------+------------+-------+---------------+---------+---------+------+------+---------------------------------+
使用'先解釋第一個查詢'然後'解釋第二個查詢'並在問題中分享結果。 –