简体   繁体   English

在mysql中将两列合并为一列

[英]Combine two columns to one in mysql

Suppose I have a table with the columns: 假设我有一个包含列的表:

`id`,`firstname`,`lastname`

With some rows like: 有些行如:

'1','bob','marley'
'2','mary','jane'

And i have a search query something like this (where 'bob marley' is my search term): 我有一个像这样的搜索查询(其中'bob marley'是我的搜索词):

select * where
(`firstname` like 'bob marley%')
or
(`lastname` like 'bob marley%')

But this only gets a hit if i search for either 'bob' or 'marley', but not 'bob marley' How can I concatenate two columns to match a search term? 但是,如果我搜索'bob'或'marley',而不是'bob marley',那么这只会受到影响我如何连接两列以匹配搜索词?

edit: The table will have hundreds of thousands of rows so performance is critical. 编辑:该表将有数十万行,因此性能至关重要。 is concat() efficient enough to work in an ajax search with delayed keystroke calls? concat()是否足够高效,可以在延迟按键调用的ajax搜索中工作? or should i redesign my table or add a fulltext column for searching? 或者我应该重新设计我的表格或添加全文列进行搜索?

使用MySQL的CONCAT功能:

SELECT * FROM tablename WHERE CONCAT(firstname, ' ', lastname) LIKE 'bob marley%'

This will destroy your query performance, but you can use concat_ws to combine them with a space in between. 这会破坏您的查询性能,但您可以使用concat_ws将它们与中间的空间组合。

select *
from tbl
where concat_ws(' ', firstname, lastname) like '%bob marley%'

Notice that I have switched your right-sided-% to double-sided-% . 请注意,我已将right-sided-% 切换double-sided-% This is necessary otherwise when searching using just marley, 'marley%' will not match. 这是必要的,否则当使用marley搜索时,'marley%'将不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM