我有兩個表在同一個數據庫Device
和EventData
;兩個表都有accountID
和deviceID
列,這些列也是主鍵。MySQL查詢與子查詢慢
在Device
表中有一列名爲linkDescription
的列。
我需要複製一些行,表EventData
,其accountID
和deviceID
,在Device
表,具有linkDescription
列一些文本。
例子:
器表
accountID DeviceID linkDescription
12345 5800 444
12345 5700 445
12345 5500 null <--literally null
12388 4400 555
12388 4450 555
EVENTDATA表
accountID DeviceID timestamp
12345 5800 123335544
12345 5700 123335544
12345 5500 123335544
12388 4400 123335544
12388 4450 123335544
12345 5800 123335548
12345 5700 123335549
12345 5500 123335549
12388 4400 123335545
12388 4450 123335546
現在我需要使用linkDescription
從重複上EventData
一些行,改變表;所以EventData
現在有以下數據:
accountID DeviceID timestamp
12345 5800 123335544
12345 5700 123335544
12345 5500 123335544
12388 4400 123335544
12388 4450 123335544
12345 5800 123335548
12345 5700 123335549
12345 5500 123335549
12388 4400 123335545
12388 4450 123335546
444 5800 123335544 <-duplicated data with new accountID from here
445 5700 123335544
555 4400 123335544
555 4450 123335544
444 5800 123335548
445 5700 123335549
555 4400 123335545
555 4450 123335546
所以現在我測試下面的查詢這將是INSERT INTO
中更大的一部分:
explain
select *
from EventData
where
EventData.accountID in (
select accountID
from Device
where Device.linkDescription > '0')
and EventData.deviceID in (
select deviceID
from Device
where Device.linkDescription> '0')
and timestamp > (unix_timestamp(now()-interval 20 minute));
不過是二慢,EXPLAIN
命令顯示此:
ID select_type table type posible_keys key key_len ref rows Extra
1 PRIMARY EventData ALL null null null null 47555718 Using where
3 DEPENDENT SUBQUERY Device ALL null null null null 8043 Using where
2 DEPENDENT SUBQUERY Device index_subquery PRIMARY PRIMARY 34 func 3 Using where
所以,據我瞭解,至少,是檢查整個表,這就是爲什麼如此緩慢。
我該怎麼做我想要的更快?
嘗試使用'JOIN's。 – Kermit 2013-05-07 18:25:17
'in'條件可以很好地處理確定性集合(例如:in(1,2,3,5)',但對於子查詢它們可能是災難性的,因爲子查詢需要爲每一行計算一次。做到這一點 – Barranka 2013-05-07 19:40:33
我有一個寫在EventData表上的JAVA模塊,所以我想我會重新編寫代碼來做我想做的事情。我有一個VB.NET程序並且按照你說的做類似的事情查詢分開,並創建一個新的查詢,所有內部的IN;因此不需要子查詢 – 2013-05-07 20:27:04