我目前正在爲較小的網站構建一個小型CMS。現在我想提取text_content
字段中的所有單詞,並將它們存儲在我的word
表中供以後分析。從SQL中的文本字段中提取單詞
page(id int,
title varchar(45),
# ... a bunch of meta fields ...
html_content text,
text_content text);
word(page_id int, # Foreign key
word varchar(100)); # I presume there are no words longer than 100 chars
目前我正在使用下面的代碼,對於較大的文本塊運行速度非常緩慢(可以理解)。
// Sidenote: $_POST is sanitized above scope of this code.
$_POST['text_content'] = str_replace("\t", "",
htmlspecialchars_decode(strip_tags($_POST['html_content'])));
// text is in swedish, so we add support for swedish vowels
$words = str_word_count($_POST['text_content'], 1, "åäöÅÄÖ");
// Delete all previous records of words
$this->db->delete("word", array('page_id' => $_POST['id']));
// Add current ones
foreach($words as $word)
{
if (trim($word) == "")
continue;
$this->db->query("INSERT INTO word(page_id, word) VALUES(?, ?)",
array($_POST['id'], strtolower(trim($word))));
}
現在,我不滿意這個解決方案。我正在考慮在數據庫中創建一個觸發器,它與php版本幾乎完全相同。 是否有可能在MySQL中創建觸發器來執行所述操作(如果有的話) - 如何?或者,還有更好的方法?我對此採取瘋狂的方法嗎?
謝謝。我不知道你可以這樣做。現在執行45秒的時間現在在0.9秒內執行。這解決了我的問題:) – 2009-10-30 20:00:42
絕對。從客戶端到服務器通信,每個查詢都有相當大的開銷。此外,blurb可以傳遞到一個存儲過程,將其分解並執行插入操作 – 2009-10-30 20:01:45