Mysql 类似 '%search%' 找不到连续列

标签 mysql sql-like concatenation

我创建了这个表:

create table if not exists `example`(
`firstNames` varchar(45) not null,
`secondNames` varchar(45) not null)
ENGINE = InnoDB;

现在我插入一行:

insert into example values('Jose Alonzo', 'Pena Palma');

并检查是否正确

select * from example;

| firstNames | secondNames |
----------------------------
| Jose Alonzo|  Pena Palma |

还好啦! 简单的 现在我创建一个语句来搜索这一行

set @search = 'jose alonzo pena';
select * from example
where concat(firstNames, ' ', secondNames) like concat('%',@search,'%');

本次回归

| firstNames | secondNames |
----------------------------
| Jose Alonzo|  Pena Palma |

现在我更改“jose pena”的值@search

set @search = 'jose pena';
select * from example
where concat(firstNames, ' ', secondNames) like concat('%',@search,'%');

并且不要返回任何内容!

| firstNames | secondNames |

发生了什么事? 我不能对 varchar 中间的字符使用 like 吗?

最佳答案

不,不能对字符串中间的字符使用 like。或者,换句话说,空格字符匹配空格字符,而不是任意字符串。以下内容将匹配:

where concat(firstNames, ' ', secondNames) like concat('%', replace(@search, ' ', '%'), '%')

顺序很重要,因此这将匹配 concat(firstNames, ' ', secondNames)但不是concat(secondNames, ' ', firstNames) .

如果您对这些类型的搜索感兴趣,您应该调查 full text indexes 。除了更强大之外,它们的速度也更快。

关于Mysql 类似 '%search%' 找不到连续列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27085125/

相关文章:

mysql - SQL - 如何搜索包含反斜杠的字符串

mysql - 在 MySQL 中将 2 行连接成单行

mysql - 检测关联表中的空行并打印出虚拟数据

php - 通过表单 Cookie 和 GET

mysql - 如何将急切加载的 Eloquent 查询更改为简单的 mysql 查询

excel - 在Excel中连接单元格忽略空白单元格

php - 连接数据库中的相同数组(数字)

sql - MySQL查询相关问题

java - 像 %?% 不能作为 StringBuilder SQL 查询的一部分

带有 SQLite LIKE 的 Android 自动完成部分工作