简体   繁体   中英

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):

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?

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? 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.

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

Notice that I have switched your right-sided-% to double-sided-% . This is necessary otherwise when searching using just marley, 'marley%' will not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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