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 开发者_C百科keystroke calls? or should i redesign my table or add a fulltext column for searching?
Use MySQL's CONCAT
function:
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.
精彩评论