views:

62

answers:

1

I need a some stored procedure that called like:

search('foo bar')

makes a search similar to:

SELECT FROM A, B
WHERE A.B_ID = B.ID
AND (A.f1 LIKE '%foo%' OR A.f2 LIKE '%foo%' OR B.f3 LIKE '%foo%')
AND (A.f1 LIKE '%bar%' OR A.f2 LIKE '%bar%' OR B.f3 LIKE '%bar%')

And I have some doubts and questions:

  1. I can't pass an array to the procedure, so my only option is to pass the string directly as in the example ('foo bar')?

  2. So I assume I have to do the split in SP code. I didn't know how, so I searched and found this solution. Is using temporary tables and what I think a lot of clumsy code. Is really so complicated? How about the performance?

  3. I don't know how to create such dynamic query. I suppose I have to loop over the tokens to create a new block of the WHERE clause for everyone, but I'm not sure how to do this or if it's the best solution. Maybe concatenating strings and then making a prepared statement is better?

Thanks.

Note: I use iBATIS (Java) for calling this routine.

+3  A: 

What you want is to use Full Text Searching (FTS) - there's MySQL's native FTS functionality which can only be used on MyISAM tables, and 3rd party FTS like Sphinx, to choose from. Here's an online slideshow that's a decent intro & howto.

Using MySQL native FTS, your query would resemble:

SELECT *
  FROM A AS a
  JOIN B AS b ON b.id = a.b_id
 WHERE MATCH (a.f1, a.f2, b.f3) AGAINST ('foo bar');

Dynamic SQL is still an option, depending on how strong you want/need to make the query. I'd look into the FTS offerings before I'd consider dynamic SQL...

OMG Ponies
Thanks. I can't do this kind of search because we are using InnoDB tables (fortunately). I'd look into Sphinx, but I think installing a new module won't be a tolerated action for the client. If this can't be achieved simply using stored procedures, I think generating the query using Java would be a better option. I'm wrong?
Sinuhe
@Sinuhe: That sucks :( I'd really try to make a strong case for using Sphinx - show how fast both solutions are. I think that generating the query using dynamic SQL in MySQL would be better than from Java - Java will require sending the entire query over when a MySQL stored procedure would just need the parameters.
OMG Ponies
Well, the truth is I finally generate the query using iBATIS. I think installing and mantaining Sphinx is not so mandatory for this simple use case. What problem do you see there, bandwith overhead?
Sinuhe
@Sinuhe: Yeah, looking at saving bandwidth when sending to MySQL. Premature optimization on my part...
OMG Ponies