创建搜索查询

时间:2013-10-28 15:46:58

标签: mysql sql search

我有一个名为Customers的表格,列FirstName, LastName, Email

让我假装我有客户:John |威廉姆斯| johnW1234@gmail.com

现在如何创建我的查询,以便我搜索:

"williams"       =>  match
"will john"      =>  Match
"will john 55"   =>  NO match
"will 1234"      =>  match

我的查询现在看起来像:

SELECT * FROM `Customers` WHERE `FirstName` LIKE _search_ OR `LastName` LIKE _search__

但是,如果有人在哪里寻找“将约翰”,那么我的查询将不会返回匹配

4 个答案:

答案 0 :(得分:1)

我认为这有效:

select * from Customers
where (_search_ regexp '^[^ ]+ [^ ]+$' or _search_ regexp '^[^ ]+$')
and (LastName like concat(substring_index(_search_, ' ',  1), '%'))
or FirstName like concat(substring_index(_search_, ' ',  -1), '%')));

答案 1 :(得分:1)

好像你想做那样的事情:

select * from Customers where 
(FirstName like concat('%','john', '%') and LastName like concat('%','smith', '%'))
or
(LastName like concat('%','john', '%') and FirstName like concat('%','smith', '%'))

部分:johnsmith(在查询中)是搜索字词的不同部分,由空格分解并修改为小写(您可以在代码中或在DB)。

链接到 Fiddle

答案 2 :(得分:0)

动态sql可以帮助你

 EXECUTE 'SELECT * FROM Customers WHERE FirstName LIKE ' ||
 _search_ || ' OR LastName LIKE ' || _search__ || ';';

“_ search _”应该转换为文本(明确与否)。

当然,报价等着你注意。

答案 3 :(得分:0)

...粗略地

SET @string = 'John|Williams|johnW1234@gmail.com';

SELECT IF(@string LIKE "%will%",IF(@string LIKE "%john%",IF(@string LIKE "%55%",1,0),0),0)x;
+---+
| x |
+---+
| 0 |
+---+

SELECT IF(@string LIKE "%will%",IF(@string LIKE "%john%",IF(@string LIKE "%12%",1,0),0),0)x;
+---+
| x |
+---+
| 1 |
+---+