【发布时间】:2017-04-12 14:09:58
【问题描述】:
找到了其他一些帖子,但没有一个对我有真正的帮助(也许我太笨了,无法搜索)。甚至在键入此内容时 Similar Questions 块也无济于事。
这是我的问题: 我有一个 mysql 数据库,有 4 列:id、first-name、last-name、city
在一个 php 应用程序上,我有一个输入字段,它通过 AJAX 查询 php 脚本以搜索数据库。如果只给出 1 个搜索词,例如名字,则此字段有效。当我尝试 2 或 3 个搜索词时,我不知道如何查询数据库。
请帮助我如何查询我的数据库(大约有 20,000 行)。
一些搜索示例:
Thomas Boston
Michael Smith New York
Doe, Jane
Orlando, Michael
预期结果是包含任何这些搜索词的所有行。最好是按相似度排序(首先找到大多数术语)。使用DIFFERENCE() 也不错,但我的脚本是德语的......
我已经阅读了有关全文搜索的资料,但不知道该怎么做。
这是我当前的查询代码(1 个搜索词):
$key = $_GET['key'];
//Here will be something to filter all non numbers/letters and change them to a space for $key
$keys = explode(" ",$key); //$keys is not in use yet
$prep_stmt = "
SELECT
id, last-name, first-name, city
FROM
customers
WHERE
last-name LIKE concat('%', ? ,'%') OR
first-name LIKE concat('%', ? ,'%') OR
city LIKE concat('%', ? ,'%')
ORDER BY
last-name ASC";
$stmt = $mysqli->prepare($prep_stmt);
$stmt->bind_param('sss', $key, $key, $key);
关于安全性:此代码在内部环境中运行。所以安全不是最重要的。
PS:我的母语不是英语,但我已经尽力了。
我找到的东西,但没有帮助:
- Performing a search on first and last name columns with a single search string that has more than 2 words
- Searching full name or first or last name in MySQL database with first and last name in separate columns
- Search with full name instead of just first name or last name
- Live search on first, middle and last name
- Search Database by First and Last Name
- MySQL Search For Names - Separated by Space
~~编辑~~
我想出的东西,但没有用:
$key = trim(preg_replace( '/\s+/', ' ', preg_replace("/[^[:alnum:][:space:]]/u", ' ', $key)));
SELECT
id, last-name, first-name, city
FROM
customers
WHERE
last-name LIKE concat('%', REPLACE( ? ,' ','%') ,'%') OR
first-name LIKE concat('%', REPLACE( ? ,' ','%') ,'%') OR
city LIKE concat('%', REPLACE( ? ,' ','%') ,'%')
ORDER BY
name ASC
【问题讨论】:
-
如果你从你的 AJAX 传递一些合理的组织良好的参数,这会让你的喜欢变得容易得多.目前,您如何区分名字、姓氏或城市?
-
这会很好也很容易,但我无法控制用户。只有一个输入字段,用户必须能够以您能想到的任何方式搜索名字、姓氏和城市。