tags:

views:

50

answers:

4

Hi all,

How to search multiple values separated by commas.

ex:

table name : searchTest

id    name      keyword

1     trophy1   test1,test2,test3

2     trophy2   test2,test5

Points:

  1. If i search for test2 both results trophy1 and trophy2 should be display.

  2. If i search for trophy1 then trophy1 should be as result.

How to solve this issue.

thanks in advance

A: 

You can use like.

select * from searchTest where keyword like '%test2%'

Where the % is a wildcard.

Gazler
Just a note : this will match a line containing something such as `test1,blahtest2glop,test3` ;;; i.e. it doesn't match only *full-tags*, but partial ones as well.
Pascal MARTIN
+1  A: 

These keywords must be stored in the separate table

Col. Shrapnel
+3  A: 

I would say that, here, your data structure is quite not right.

It would be a better solution to not store several values in one field using some comma-separated format, but use three tables, defined this way :

  • searchtest
    • id
    • name
  • keywords
    • id
    • word
  • keywords_searchtest
    • id_keyword
    • id_searchtest


With that, searching for entries in searchtest that have specific keywords would be as simple as :

select searchtest.*, keywords.*
from searchtest
    inner join keywords_searchtest on keywords_searchtest.id_searchtest = searchtest.id
    inner join keywords on keywords.id = keywords_searchtest.id_keyword
where keywords.word = 'test2'


And, additionnaly, you'd have to search for searchtest entries with a specific name :

select *
from searchtest
where name = 'trophy1'
Pascal MARTIN
Since this is ultimately going to be a search being driven by some input, the first query could be used to accomplish both searches by using an OR clause adding (not adjusted for coding language): keywords.word = var OR searchtest.name = var
Joel Etherton
i agree with Etherton. Martin can you please explain what is the need of two queries.
Fero
@Fero : I actually agree with @Joel, in at least most cases ; the only situation where you'll need two queries is if a name doesn't have any keyword : the inner join will fail, in such situations, and return no line *(not tested, but this is what should happen)*
Pascal MARTIN
oh that's quite right Martin. I didn't think of it. Thanks for your response
Fero
You're welcome :-)
Pascal MARTIN
+2  A: 

Hello,

For Point 1 : select * from searchTest where keyword like LIKE '%test2%

For Point 2 : select * from searchTest where name like LIKE 'trophy1%

Kanak Vaghela