views:

37

answers:

2

I have a table of first and last names

firstname    lastname
---------    ---------
Joe          Robertson
Sally        Robert
Jim          Green
Sandra       Jordan

I'm trying to search this table based on an input that consists of the full name. For example:

input: Joe Robert

I thought about using

SELECT * FROM tablename WHERE firstname LIKE

BUT the table stores the first and last name separately, so I'm not sure how to do the search in this case

+4  A: 

In MyISAM:

SELECT  *
FROM    mytable
WHERE   MATCH(firstname, lastname) AGAINST ("Joe* Robert*" IN BOOLEAN MODE);

This will run much faster if you create a FULLTEXT index:

CREATE FULLTEXT INDEX ON mytable (firstname, lastname)

For the query to be able to search the short names (like Joe in your case), you'll need to set the variable @@ft_min_word_len to 1 before creating the index.

In InnoDB you'll need to split the search string:

SELECT  *
FROM    mytable
WHERE   firstname LIKE 'Joe%'
        AND lastname LIKE 'Robert%'
Quassnoi
running a query in boolean mode without a full text search is slow so i would not recommend that.and modifying server variables like '@@ft_min_word_len' is not ideal cz most of the time you cannot edit the mysql config file.The simplest would be the query you have mentioned using like and wildcard
ovais.tariq
+2  A: 

An alternative to Quassnoi's method:

SELECT  *
FROM    mytable
WHERE   CONCAT(firstname, " ", lastname) = "Joe Robert"
Scharrels
It will be terribly slow but it should work. You may want to use single quotes in the query.
Salman A
For exact match semantics, it is not slower than the fulltext query without the index. But it seems that the @op wants partial matches and this query won't match names like `Joel Robertson`
Quassnoi