tags:

views:

51

answers:

3
+1  Q: 

sql IN operator

Hi. I have the sql below but can not get it to work

select product_category, 
       (
        select top 1 sub_category 
          from sub_categories 
         where product_category IN (keywords)
       ) as s 
  from products;

product category is Baby Gift Baskets and the keywords field is Baby Gift Baskets,Baby Gifts

basically want to get sub_category when product_category is found in the keywords list?

A: 

This will not work for you, as the keywords is seen as a single item.

You will have to split the values from keyword to be able to use an IN

Have a look at

Split Function

or

Split XML style

astander
+4  A: 

You would need to use

where ',' + keywords + ',' like '%,'+ product_category + ',%'

this would be much easier and more efficient with a normalised database structure. (Your current structure with multiple keywords in a single column violates first normal form)

Martin Smith
+1 "violates first normal form"
onedaywhen
This is a better solution than the accepted one, it deals with keywords that can be part of larger keywords, ie. "Gifts" vs. "Baby Gifts".
Lasse V. Karlsen
A: 

This will not work. You can change this to use LIKE -

select top 1 sub_category 
  from sub_categories 
 where keywords like '%' + product_category + '%';
Sachin Shanbhag
awesome thanks!
Alessandro
@Alessandro - I agree, Martin Smith's answer is better. I dint see that flaw in my answer.
Sachin Shanbhag