【问题标题】:Search keyword(s) that matches data in MySQL搜索与 MySQL 中的数据匹配的关键字
【发布时间】:2012-09-05 05:52:36
【问题描述】:

我正在整理图书馆系统并修复凌乱的书名。 我想写一个 SQL 查询或 PHP 代码,在一个句子中搜索与 MySQL 表中的数据匹配的关键字。

[tbl_keywords]

id | keyword             | title
====================================================================
 1 | Harry Potter        | Harry Potter
 2 | Philosopher's Stone | [Harry Potter] Harry Potter and the Philosopher's Stone
 3 | Chamber of Secrets  | [Harry Potter] Harry Potter and the Chamber of Secrets
 4 | Dr. Seuss           | Dr. Seuss
 5 | Green Eggs and Ham  | [Dr. Seuss] Green Eggs and Ham
 6 | The Cat in the Hat  | [Dr. Seuss] The Cat in the Hat

例如,

"Harry Potter(1)" => matches 1
"[Harry Potter] Harry Potter and the Philosopher's Stone(1)" => matches 1 and 2
"(HARRY POTTER2) THE CHAMBER OF SECRETS" => matches 1 and 3
"Dr. Seuss - Green Back Book" => matches 4
"Green eggs and ham" => matches 5
"the cat in the hat(Dr. Seuss)" => matches 4 and 6

这也可能(易于实现)吗?如果做的太多,我只是将变量值添加到表中..

"HarryPotter" => matches 1
"Dr.Seuss" => matches 4
"Dr Seuss" => matches 4

任何有关如何执行此操作的帮助或想法将不胜感激。提前致谢。

【问题讨论】:

标签: php mysql search


【解决方案1】:

在你的 SQL where 条件中使用 LIKE。

例子:

$input_search //your search input
$sql1 = 'Select * from `tbl_keywords` where keyword ="'.$input_search.'"';
//...the rest of code
$sql2 = 'Select * from `tbl_keywords` where keyword LIKE "%'.$input_search.'%" OR title LIKE "%'.$input_search.'%"';
//... the rest of code
//here is IF condition to get the desire result from the sql result you got

【讨论】:

  • 谢谢,但我想检查一下 $input_search 是否有关键字在表中。
【解决方案2】:

Jst是这样写的

$element_to_search='//get here the input to search';
$sql2 = 'Select * from `tbl_keywords` where keyword LIKE "%'.$element_to_search.'%" OR title LIKE "%'.$element_to_search.'%"';

在您的情况下,始终将要搜索的 key_element 放在两个“%HERE%”之间,因为

"HERE%" 将得到键以 and 开头的结果

"%HERE" 将返回其键以, 结尾的结果

但如果你输入“%HERE%”,它将导致所有包含“key_element”作为子字符串的元素。 谢谢

【讨论】:

  • 谢谢,但我想做的是相反的方向,在 $element_to_search 的表中搜索关键字。 $element_to_search="[哈利波特] 哈利波特与魔法石(1)";
【解决方案3】:

PHP stristr 用于查找数组中的每个关键字,而不是 SQL。

search in text , and select keywords by php

然后,在 MySQL 表中查找 ID 以获取其他信息/字段;标题、类别等

$keywords = array(NULL, 'Harry Potter', 'Philosopher\'s Stone', 'Chamber of Secrets');
$input_title = "[Harry Potter] Harry Potter and the Philosopher\'s Stone(1)"

$keyword_found = array();
foreach ($keywords as $key => $val) {
    if (stristr($input_title, $val)) $keyword_found[] = $key;
}

if ($keyword_found) {
    foreach ($keyword_found as $val) {
        $sql = "SELECT * FROM `tbl_keywords` WHERE `id` = '" . $val . "'";
        ...
    }
}

它并不整洁,必须有更好的方法,但是.. 至少它有效! 再次感谢那些试图帮助我的人:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 2012-09-20
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多