3

I need to select any occurrence of a word (keyword search) on two tables and the query I made is like this:

SELECT t1.fname, t1.lname, t2.* FROM t1 , t2  
     WHERE t2.title LIKE "%test%" 
     OR t2.desc LIKE "%test%" 
     OR t2.inc LIKE "%test%" 
     OR t1.fname LIKE "%test%" 
     OR t1.lname LIKE "%test%" 
     AND t1.c_id = t2.c_id;

As there is a lot of data in database, this particular search (with 'test' keyword) takes several minutes and I'm wondering how to optimize this. I tried with LEFT JOIN but it seems I did it wrong - as the results defers pretty much, but it the query is executed very quickly.

It is like this:

SELECT * FROM t2 AS a 
  LEFT JOIN t1 AS b ON a.c_id = b.c_id 
    WHERE a.desc LIKE '%test%' 
     OR a.title LIKE '%test%' 
     OR a.inc LIKE '%test%' 
     OR b.fname LIKE '%test%'  
     OR b.lname LIKE '%test%';

Any help would be much appreciated ... thanks.

4
  • Whach database engine you are using? Commented Jan 9, 2013 at 7:53
  • MyIsam ... tables were built before, I'm fixing bugs Commented Jan 9, 2013 at 8:03
  • 1
    If you have MyISAM tables then you can use MATCH..AGAINST keywords to search a string in multiple columns. Check my answer it will give you the idea of how to use MATCH..AGAINST in query Commented Jan 10, 2013 at 14:57
  • yes, I wanted to ... but not all of them are MyISAM :( Commented Jan 15, 2013 at 14:21

2 Answers 2

2

You first statement is not what you intended: theAND clause takes precedence over OR so you have actually written

t2.title LIKE "%test%" 
OR t2.desc LIKE "%test%" 
OR t2.inc LIKE "%test%" 
OR t1.fname LIKE "%test%" 
OR (t1.lname LIKE "%test%" AND t1.c_id = t2.c_id;)

This finally results in a (somewhat skewed) natural join between t1 and t2 returning far to many rows.

Sign up to request clarification or add additional context in comments.

3 Comments

yes, must have been right - the results are not ok. I tried what you suggested, but it is the same. I assume, Left join would be better?
@Angel M - I haven't suggested anything, merely showed you the error in your original statement. I don't know your use case but I think you should replace the LEFT JOIN with an FULL OUTER JOIN to get results from either t1 or t2.
I meant - showing me the error - and I found a way - and now I had the right results.
2

Try MATCH..AGAINST to search multiple columns for MyISAM tables:

SELECT * 
FROM t2 AS a 
INNER JOIN t1 AS b ON a.c_id = b.c_id 
WHERE MATCH (a.desc, a.title, a.inc, b.fname, b.lname) AGAINST ('test') 

Check this link MYSQL FULL TEXT SEARCH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.