Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for all combinations of first, middle and last name

Tags:

sql

mysql

In my database there is a table called author, which 4 columns:

  • authorID
  • firstName
  • middleName
  • lastName

A user, for example, is searching for Edgar Allan Poe. In our table Edgar Allan Poe is saved as: firstName- Edgar, middleName - Allan and lastName - Poe. This query is pretty straightforward. But how to write a query that matches not only Edgar Allan Poe, but also Poe Allan Edgar, Edgar Poe, Allan Poe, Edgar Allan, Allan Edgar Poe without writing all these possible combinations on our own? Also when the user is searching, he/she is searching as 'Edgar Allan Poe' or 'Poe Allan Edgar' altogether, not in a separate fields.

like image 930
Xty83a Avatar asked May 08 '17 01:05

Xty83a


People also ask

How do I combine first name middle name and last name in Oracle?

Let's say you want to create a single Full Name column by combining two other columns, First Name and Last Name. To combine first and last names, use the CONCATENATE function or the ampersand (&) operator.

How do I put space between first name and last name in SQL?

How do I put space between first name and last name in SQL? SELECT FirstName, MiddleName, LastName, Firstname + ' ' + ISNULL(MiddleName,'') + ' ' + LastName AS FullName FROM tbStudent. But if the middle name is null then there will be two spaces instead of one space in between first and last name as shown below.

How can I join two names in SQL?

The CONCAT() function adds two or more strings together. Note: See also Concat with the + operator and CONCAT_WS().


1 Answers

In any database, you can do something like this:

where firstName in ('Edgar', 'Allan', 'Poe') and
      middleName in ('Edgar', 'Allan', 'Poe') and
      middleName <> firstName and
      lastname in ('Edgar', 'Allan', 'Poe') and
      lastname not in (firstname, middleName)

This is actually pretty easy to extend to more names, if you like -- assuming the names are distinct as in your example (if you want to allow authors with duplicated names, just remove lines 3 and 5 from the above query).

However, depending on your database, you might want to use regular expressions or full text search instead.

like image 158
Gordon Linoff Avatar answered Sep 29 '22 07:09

Gordon Linoff