23

在我的 SQL 中,我使用WHEREandLIKE子句来执行搜索。但是,我需要对两列的组合值执行搜索 -first_namelast_name

WHERE customers.first_name + customers.last_name LIKE '%John Smith%'

这不起作用,但我想知道我怎么能按照这些思路做点什么?

我试图通过两列分开搜索,如下所示:

WHERE customers.first_name LIKE '%John Smith%' OR customers.last_name LIKE '%John Smith%'

但显然这行不通,因为搜索查询是这两列的组合值。

4

3 回答 3

36

使用以下内容:

WHERE CONCAT(customers.first_name, ' ', customers.last_name) LIKE '%John Smith%'

请注意,为了使其按预期工作,应该修剪名字和姓氏,即它们不应包含前导或尾随空格。在插入数据库之前,最好在 PHP 中修剪字符串。但是您也可以像这样将修剪合并到您的查询中:

WHERE CONCAT(TRIM(customers.first_name), ' ', TRIM(customers.last_name)) LIKE '%John Smith%'
于 2012-04-25T23:25:42.317 回答
2

我会从这样的事情开始:

WHERE customers.first_name LIKE 'John%' AND customers.last_name LIKE 'Smith%'

这将返回如下结果:John Smith, Johnny Smithy, Johnson Smithison,因为百分号仅位于LIKE子句的末尾。不像'%John%'which 可能会返回类似的结果:aaaaJohnaaaa, aaaSmithaaa.

于 2012-04-25T23:30:49.490 回答
1

试试这个:

SELECT * 
FROM customers 
WHERE concat(first_name,' ',last_name) like '%John Smith%';

参考:
MySQL 字符串函数

于 2012-04-25T23:57:08.530 回答