mitch
mitch

Reputation: 155

MySQL search multiple columns for a match

I have a search that searches for a match through several columns in multiple tables. The issue is that I am using "OR" but this does not work if the user searches multiple columns.

Here is my query:

    SELECT clients.clientName,
       projects.Client_ID,
       projects.projectNumber,
       projects.projectName,
       projects.projectManager,
       projects.expectedDate,
       projects.address,
       projects.CreationDate,
       projects.custom1,
       projects.custom2,
       projects.custom3,
       projects.custom4,
       projects.custom5,
       projects.custom6,
       projects.custom7,
       projects.custom8,
       projects.custom9,
       projects.Status_ID,
       statuses.status
FROM projects
JOIN clients ON projects.Client_ID = clients.Client_ID
JOIN statuses ON  projects.Status_ID = statuses.Status_ID
WHERE clientName LIKE '%$keyword%'
  OR projectNumber LIKE '%$keyword%'
  OR projectName LIKE '%$keyword%'
  OR address LIKE '%$keyword%'
  OR area LIKE '%$keyword%'
  OR status LIKE '%$keyword%'
  OR custom1 LIKE '%$keyword%'
  OR custom2 LIKE '%$keyword%'
  OR custom3 LIKE '%$keyword%'
  OR custom4 LIKE '%$keyword%'
  OR custom5 LIKE '%$keyword%'
  OR custom6 LIKE '%$keyword%'
  OR custom7 LIKE '%$keyword%'
  OR custom8 LIKE '%$keyword%'
  OR custom9 LIKE '%$keyword%';  

If the user searches: a status and client --my query will not return any results.

Also, I am worried about the speed of this query with a lot of data.

Upvotes: 2

Views: 3335

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562230

You're right, the type of query you're using will force a table-scan, and it cannot be indexed. This is still true even if you only search a single column with LIKE '%$keyword%'

The only efficient way to do full text search is with special fulltext indexing technology. MySQL has this built in, but only for MyISAM tables currently (fulltext indexes will be supported in InnoDB in MySQL 5.6).

You should read my presentation: Full Text Search Throwdown for a comparison of different solutions. It's clear from the testing I did that using LIKE runs hundreds or thousands of times slower than using any type of text indexing. How much slower depends largely on the size of your table.


Re comment from @Dagon:

I originally did this presentation in 2008, but I updated it and re-ran all my tests in April 2012. The differences from my 2008 presentation were insignificant.

Any indexing solution is still orders of magnitude better than the costly table-scans you get with LIKE. The larger your table, the greater the benefit of indexing. This principle is not going to change.

Upvotes: 3

Related Questions