2014-10-07 45 views
0

我有一個數據庫,只有超過1000萬行。下面是結構:MySQL的查詢(根據連接更新每一行)

CREATE TABLE IF NOT EXISTS `map` (
    `id` int(11) NOT NULL, 
    `good` tinyint(1) NOT NULL DEFAULT '0', 
    `x` int(11) NOT NULL, 
    `y` int(11) NOT NULL, 
    `terrian_type` int(11) NOT NULL, 

    ... 6 more int columns 

    PRIMARY KEY (`id`), 
    KEY `x` (`x`), 
    KEY `y` (`y`), 
    KEY `terrian_type` (`terrian_type`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

這包含在世界地圖,其中(x,y)被定義爲一個特定正方形的座標。每個廣場都有一個地形類型。

我想要做的是更新每個廣場,用布爾(「好」)。如果8個周圍的正方形都具有相同的terrain_type(所討論的正方形無關緊要),則將正方形分類爲「良好」。

這裏是我的查詢,以辨別1特異平方米/排好(X,Y)=(5,5):

SELECT 
    COUNT(in1.terrian_type), 
    in1.terrian_type 
FROM `worldmap` w1 
INNER JOIN `worldmap` in1 
    ON in1.x >= w1.x-1 
    AND in1.x <= w1.x+1 
    AND in1.y >= w1.y-1 
    AND in1.y <= w1.y+1 
    AND IF(in1.y = w1.y, IF(in1.x = w1.x, 0, 1), 1) = 1 
WHERE w1.x = '5' 
AND w1.y = '5' 
GROUP BY in1.terrian_type 

如果超過1行回來了,這是不是 「好」 。

希望有人可以幫助確定每個廣場是否好(每個1000萬)。使用上面的查詢遍歷每一個將花費太長時間!這隻需要每月進行一次。

問候, 馬特

回答

0

以下長相醜陋而可能不是太有效的(除非你有X和Y指標),但我認爲這應該工作:

SELECT maptext.x, maptest.y, IF(maptext.terrian_type = x1y.terrian_type AND maptext.terrian_type = x1y1.terrian_type AND maptext.terrian_type = xy1.terrian_type AND maptext.terrian_type = x_1y1.terrian_type AND maptext.terrian_type = x_1y.terrian_type AND maptext.terrian_type = x_1y_1.terrian_type AND maptext.terrian_type = xy_1.terrian_type AND maptext.terrian_type = x1y_1.terrian_type, 'GOOD','BAD') 
    FROM worldmap maptest 
    INNER JOIN worldmap x1y 
    on maptest.x = x1y.x + 1 and maptest.y = x1y.y 
    INNER JOIN worldmap x1y1 
    on maptest.x = x1y1.x + 1 and maptest.y = x1y1.y + 1 
    INNER JOIN worldmap xy1 
    on maptest.x = xy1.x and maptest.y = xy1.y + 1 
    INNER JOIN worldmap x_1y1 
    on maptest.x = x_1y1.x - 1 and maptest.y = x_1y1.y + 1 
    INNER JOIN worldmap x_1y 
    on maptest.x = x_1y.x - 1 and maptest.y = x_1y.y 
    INNER JOIN worldmap x_1y_1 
    on maptest.x = x_1y_1.x - 1 and maptest.y = x_1y_1.y - 1 
    INNER JOIN worldmap xy_1 
    on maptest.x = xy_1.x and maptest.y = xy_1.y - 1 
    INNER JOIN worldmap x1y_1 
    on maptest.x = x1y_1.x + 1 and maptest.y = x1y_1.y - 1 
+0

這一個查詢了約平均5.4s(5.4sx 8m =很多)。雖然謝謝! – mattwt 2014-10-07 16:27:33