作者weiclin (CC)
看板PHP
标题Re: [请益] mysql搜寻问题
时间Tue Mar 29 14:24:50 2016
※ 引述《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://webptt.com/cn.aspx?n=bbs/PHP/M.1459232693.A.6A3.html
1F:推 shadowjohn: 写的不错 03/30 00:57
2F:推 liaosankai: 感谢,学到新 LIKE 写法 03/30 11:36
3F:推 villix: 看起来很不错~感谢大大=w= 03/30 12:39
4F:推 shadowjohn: 不过like的部分应该用prepare-s... like ? 03/30 15:24
5F:→ weiclin: 我认为用不到 prepare, 也没办法使用 prepare 03/30 16:09
9F:推 shadowjohn: 嗯嗯,查sql自身栏位可以不用用,也不需要用的:D 03/31 09:34
10F:推 GALINE: 这招有点帅,不过关键字或 message 的时候感觉 full table 04/01 08:57
11F:→ GALINE: scan 会有点苦。资料不大或是线下作业比较适合这样搞 04/01 08:57
12F:推 GALINE: 「关键字或 message 多的时候」 04/01 08:59
13F:→ GALINE: 如果是线上服务需要搜寻,建议还是弄个搜寻引擎来 04/01 09:00
14F:→ GALINE: 像是 Solr 或 Elasticsearch.... 04/01 09:01