2014-11-23 50 views
0

我创建该表:mysql的像不CONCAT colums发现 '%搜索%'

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 | 

好吧! 易 现在我创建一个statment搜索该行

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

这回

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

现在我改变 '乔斯·佩纳'

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

值@search也不要什么都不返回

| firstNames | secondNames | 

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

回答

1

不,你不能使用像字符串中间的字符。换句话说,空格字符与空格字符相匹配,而不是任意字符串。下面将匹配:

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

的顺序将是重要的,所以这会匹配concat(firstNames, ' ', secondNames)但不concat(secondNames, ' ', firstNames)

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

+0

谢谢! 这正是我想要的。 – joepa37 2014-11-23 03:16:24