2012-08-05 29 views
0

以下查詢在600秒後超時。當比較兩個表中的多個字段時,緩慢更新一個表

update placed p 
     ,Results r 
    set p.position = r.position 
    where p.competitor = r.competitor 
    AND p.date = r.date 
    AND REPLACE(p.time,":","") = r.time; 

的結構如下:

'CREATE TABLE `placed` (
    `idplaced` varchar(50) DEFAULT NULL, 
    `date` decimal(8,0) DEFAULT NULL, 
    `time` varchar(45) DEFAULT NULL, 
    `field1` varchar(45) DEFAULT NULL, 
    `competitor` varchar(45) DEFAULT NULL, 
    `field2` int(2) DEFAULT NULL, 
    `field3` varchar(45) DEFAULT NULL, 
    `field4` varchar(45) DEFAULT NULL, 
    `field5` decimal(6,2) DEFAULT NULL, 
    `field6` decimal(10,2) DEFAULT NULL, 
    `field7` decimal(6,2) DEFAULT NULL, 
    `field8` char(1) DEFAULT NULL, 
    `field9` varchar(45) DEFAULT NULL, 
    `position` char(4) DEFAULT NULL, 
    `field10` decimal(6,2) DEFAULT NULL, 
    `field11` char(1) DEFAULT NULL, 
    `field12` char(1) DEFAULT NULL, 
    `field13` decimal(6,2) DEFAULT NULL, 
    `field14` decimal(6,2) DEFAULT NULL, 
    `field15` decimal(6,2) DEFAULT NULL, 
    `field16` decimal(6,2) DEFAULT NULL, 
    `field17` decimal(6,2) DEFAULT NULL, 
    `field18` char(1) DEFAULT NULL, 
    `field19` char(20) DEFAULT NULL, 
    `field20` char(1) DEFAULT NULL, 
    `field21` char(5) DEFAULT NULL, 
    `field22` char(5) DEFAULT NULL, 
    `field23` int(11) DEFAULT NULL 
    PRIMARY KEY (`idplaced`), 
    UNIQUE KEY `date_time_competitor_field18_combo` (`date`,`time`,`competitor`,`field18`) 
) ENGINE=InnoDB AUTO_INCREMENT=100688607 DEFAULT CHARSET=latin1; 

CREATE TABLE `results` (
    `idresults` int(11) NOT NULL AUTO_INCREMENT, 
    `date` char(8) DEFAULT NULL, 
    `time` char(4) DEFAULT NULL, 
    `field1` varchar(45) DEFAULT NULL, 
    `competitor` varchar(45) DEFAULT NULL, 
    `position` char(4) DEFAULT NULL, 
    `field2` varchar(45) DEFAULT NULL, 
    `field3` decimal(2,0) DEFAULT NULL, 
    PRIMARY KEY (`idresults`) 
) ENGINE=InnoDB AUTO_INCREMENT=6644 DEFAULT CHARSET=latin1; 

PLACED表具有65000個記錄,該RESULTS表具有9000分的記錄。

我假設解決方案涉及一些描述的JOIN聲明,並且我嘗試了從這個網站得到幾個建議,但根本找不到我正在尋找的答案。簡而言之,我會很感激這方面的建議。如果需要,我可以放置示例表/創建表代碼。

+1

而不是用你自己的話來描述你的表/索引,你可以發佈每個表的'SHOW CREATE TABLE ...'的結果嗎? – 2012-08-05 22:21:54

+0

@MarkByers - 是的,對不起,應該從偏移量做到這一點。 – user1458484 2012-08-06 07:53:08

回答

0

由於您的REPLACE操作,索引無法有效地用於執行聯接。 我建議按以下順序稍有不同創建與列的索引:

(date, competitor, time, position) 

它也可以幫助這兩個表添加此指數。

如果您可以修改數據庫中的數據,以便time列中的數據以兩種表中的相同格式存儲,那將會更好。

+0

'REPLACE'確實是殺手。爲了記錄,'POSITION'從來沒有在索引中,但我確實嘗試了重新排序(在刪除'REPLACE'之前,但它沒有改變任何東西。我也無法將相同的索引應用於兩個表,因爲表'RESULT '沒有'INDEX'中的所有字段,非常感謝。 – user1458484 2012-08-06 10:54:59

0

首先,你最好向我們提供您完整表說明,使用

show create table 

其次,你最好使用聯接語法:

update placed p 
    join Results r on r.competitor = p.competitor 
    set p.position = r.position 
where p.date = r.date 
    AND REPLACE(p.time,":","") = r.time; 

希望這會有所幫助。

+1

不幸的不是。我曾試過這個,但它也超過600秒後超時。 – user1458484 2012-08-06 07:50:40