2016-02-02 33 views
1

我構建了一個生成隨機語句的邏輯。爲此,我有一個數據庫表,大約有1.000.000個包含卦的條目。如何獲取相互依賴的未定義數量的SQL查詢

目前的邏輯是:

  1. 獲得初始字
  2. 獲得基於第一個字一個字
  3. 繼續下去,直到進入比賽結束標誌

在PHP中,它看起來是這樣的

while($i < 30 && $last['three'] != '[end]') { 
    $last = getDBentry($mysqli, $last); 
    if($last['three'] != '[end]') { 
    $string .= ' ' . $last['three']; 
    } 
    $i++; 
} 

我將其限制爲最大。 30但即使只有10個字,這也需要大約15秒。是否有最佳實踐或好方法來更好地處理這些數據?

編輯

function getDBentry() { 
... 
$key = $last['two'].$last['three']; 

if($single) { 
    $sql = "SELECT * FROM trigrams WHERE gramkey = '$key'"; 
} else { 
    $sql = "SELECT * FROM trigrams WHERE gramkey = '$key' AND amount > 1"; 
} 

$matches = array(); 

if ($result = $mysqli->query($sql)) { 
    if($result->num_rows === 0 && $single) { 
     die('error no result'); 
    } 

    if($result->num_rows === 0) { 
     return getDBentry($mysqli, $last, true); 
    } 

    while($obj = $result->fetch_object()){ 
     array_push($matches, array('one' => $obj->one, 'two'=>$obj->two, 'three'=>$obj->three, 'amount'=>$obj->amount, 'gramkey'=>$obj->gramkey)); 
    } 
} else { 
    die('error'); 
} 

... 

我把關於該主題的這是非常重要的組成部分

表結構

ID,gramkey,一,二,三,量 - 其中一二三都單詞和gramkey由一個和兩個分析爲單個字符串以使其易於訪問

+0

請出示你的表結構,樣本數據,並輸出從當前的代碼,與SQL的'getDBentry()'正在執行(或全功能的定義,如果沿它很簡單) – Steve

+0

你每次運行循環時都調用數據庫嗎? – Epodax

+0

是的,我每次運行循環時都會調用db,我將在第二個函數中添加 –

回答

1

正如AlexBlex在評論中提到的,sol在文檔中可以使用ution。

通過添加col colkeys的索引,性能提升非常瘋狂。從15秒到0.1秒。

編輯:SHOW CREATE TABLE

CREATE TABLE `trigrams` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`gramkey` varchar(256) COLLATE utf8_unicode_ci NOT NULL, 
`one` varchar(256) COLLATE utf8_unicode_ci NOT NULL, 
`two` varchar(256) COLLATE utf8_unicode_ci NOT NULL, 
`three` varchar(256) COLLATE utf8_unicode_ci NOT NULL, 
`amount` int(11) NOT NULL, 
PRIMARY KEY (`id`), 
KEY `gramkey` (`gramkey`(255)) 
) ENGINE=InnoDB AUTO_INCREMENT=1055131 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci