Re: [請益] mysql搜尋問題

看板PHP作者 (CC)時間9年前 (2016/03/29 06:24), 編輯推噓7(707)
留言14則, 6人參與, 最新討論串2/2 (看更多)
※ 引述《villix (瓜子被蜀國的狗吃了)》之銘言: : 不好意思請問一下,如果現在有兩張table, table1有需要搜尋的字串, : table2裡面是有句子的字串,可以將table1的所有字串搜尋出來當作array : 然後在table2裡面搜尋有table1字串的句子嗎?希望是可以將table1的所有 : 字串在table2裡面做fulltext search 然後做count這樣~~ 大概是這樣? <?php try { $pdo = new PDO('sqlite::memory:'); $pdo->exec("CREATE TABLE 'keywords' ('keyword' TEXT);"); $pdo->exec("INSERT INTO 'keywords' ('keyword') VALUES ('google'),('bing'),('yahoo');"); $pdo->exec("CREATE TABLE 'messages' ('message' TEXT);"); $pdo->exec("INSERT INTO 'messages' ('message') VALUES ('how about google.com?'),('why not bing?'),('is yahoo good?');"); $pdo->exec("INSERT INTO 'messages' ('message') VALUES ('Captain America'),('Gundam Mark II'),('google AlphaGO');"); $result = $pdo->query("SELECT M.*, K.* FROM messages M INNER JOIN (SELECT keyword FROM keywords) K ON M.message LIKE '%' || K.keyword || '%'"); if ($result) { foreach($result as $row) { echo "found keyword [{$row['keyword']}] in message [{$row['message']}]\n"; } } $result = $pdo->query("SELECT COUNT(M.message) AS cnt, E.keyword AS keyword FROM messages M INNER JOIN (SELECT keyword FROM keywords) E ON M.message LIKE '%' || E.keyword || '%' GROUP BY E.keyword"); if ($result) { foreach($result as $row) { echo "the keyword [{$row['keyword']}] was founded in {$row['cnt']} messages\n"; } } } catch (PDOException $e) { echo "Error!: {$e->getMessage()}\n"; } 執行結果: $ php inner_join.php found keyword [google] in message [how about google.com?] found keyword [bing] in message [why not bing?] found keyword [yahoo] in message [is yahoo good?] found keyword [google] in message [google AlphaGO] the keyword [bing] was founded in 1 messages the keyword [google] was founded in 2 messages the keyword [yahoo] was founded in 1 messages -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.68.230.200 ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1459232693.A.6A3.html

03/30 00:57, , 1F
寫的不錯
03/30 00:57, 1F

03/30 11:36, , 2F
感謝,學到新 LIKE 寫法
03/30 11:36, 2F

03/30 12:39, , 3F
看起來很不錯~感謝大大=w=
03/30 12:39, 3F

03/30 15:24, , 4F
不過like的部分應該用prepare-s... like ?
03/30 15:24, 4F

03/30 16:09, , 5F
我認為用不到 prepare, 也沒辦法使用 prepare
03/30 16:09, 5F

03/30 16:31, , 6F
http://goo.gl/bn4p7q 這不就用了 作法相通
03/30 16:31, 6F

03/30 16:32, , 7F
http://goo.gl/bGSoz0 要pdo也有pdo的
03/30 16:32, 7F

03/30 16:40, , 8F
你看看這篇,理由差不多 http://goo.gl/6c8VpA
03/30 16:40, 8F

03/31 09:34, , 9F
嗯嗯,查sql自身欄位可以不用用,也不需要用的:D
03/31 09:34, 9F

04/01 08:57, , 10F
這招有點帥,不過關鍵字或 message 的時候感覺 full table
04/01 08:57, 10F

04/01 08:57, , 11F
scan 會有點苦。資料不大或是線下作業比較適合這樣搞
04/01 08:57, 11F

04/01 08:59, , 12F
「關鍵字或 message 多的時候」
04/01 08:59, 12F

04/01 09:00, , 13F
如果是線上服務需要搜尋,建議還是弄個搜尋引擎來
04/01 09:00, 13F

04/01 09:01, , 14F
像是 Solr 或 Elasticsearch....
04/01 09:01, 14F
文章代碼(AID): #1M-X-rQZ (PHP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
請益
1
6
完整討論串 (本文為第 2 之 2 篇):
請益
1
6
文章代碼(AID): #1M-X-rQZ (PHP)