【问题标题】:Mysql like '%search%' not found with concat columsMysql like '%search%' not found with concat columns
【发布时间】:2015-01-21 00:02:25
【问题描述】:

我创建了这张表:

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 |

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

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

并且什么都不返回!

| firstNames | secondNames |

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

【问题讨论】:

    标签: mysql sql-like concat


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢!这正是我想要的。
    猜你喜欢
    • 2018-07-22
    • 2019-05-12
    • 1970-01-01
    • 2016-11-22
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多