我创建了这个表:
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/