简体   繁体   中英

MySQL Stored procedure: search for a variable number of strings

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM