我想在 MySQL 数据库中搜索作者姓名。问题是同一作者姓名可以通过多种方式拼写(或输入数据库)。我需要检查是否有相似的名字。
我的
authors
表的示例如下;
+---------+-------------+
| id | author |
+---------+-------------+
| 1 | JK Rowling |
+---------+-------------+
| 2 | J.K Rowling |
+---------+-------------+
| 3 | Rowling JK |
+---------+-------------+
| 4 | Rowling J.K |
+---------+-------------+
| 5 | JK. Rowling |
+---------+-------------+
| 6 | Jim Jones |
+---------+-------------+
我想找到“J.K Rowling”的所有书籍,所以我使用的查询是;
SELECT *
FROM `authors`
WHERE `author` LIKE '%J.K Rowling%'
退货
no results
。
SELECT *
FROM `authors`
WHERE `author` LIKE 'J.K Rowling%'
退货
no results
。
SELECT *
FROM `authors`
WHERE `author` LIKE '%J.K Rowling'
退货
no results
。
我应该如何构建查询才能返回相似的作者。
谢谢
好像相似的名字是罗琳,所以我应该尝试一下。
SELECT *
FROM `authors`
WHERE `author` LIKE '%Rowling%'
那是因为您使用
%J.K Rowling%
,这意味着该过程将仅搜索具有 J.K Rowling
的行,不多也不少。根据您的数据表,上面没有J.K Rowling
。您可能想尝试Rowling
或类似的东西。
你的问题是“。”
根据 MySQL 文档,使用 LIKE 运算符时唯一的特殊字符是“%”(百分比:匹配 0、1 或多个字符)和“_”(下划线:匹配一个且仅一个字符)。 http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
一个“。” (句点) 对于 MySQL 的 REGEXP 运算符确实具有特殊含义,但它仍应与列中的字面句点匹配。 http://dev.mysql.com/doc/refman/5.0/en/regexp.html
create table authors(id integer, author varchar(100));
insert into authors(id, author) values(1, "J.K Rowling");
insert into authors(id, author) values(2, "JK Rowling");
insert into authors(id, author) values(3, "Rowling JK");
insert into authors(id, author) values(4, "Rowling J.K");
insert into authors(id, author) values(5, "JK. Rowling");
insert into authors(id, author) values(6, "Jim Beam");
SELECT *
FROM `authors`
WHERE `author` LIKE '%J.K Rowling%'
我得到的结果是:
id author
1 J.K Rowling
所以代码检查出来,应该可以工作,也许你的数据库设置有所不同。