If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Select a field if mathes to 2 or more criteria

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-17-09, 09:49
sakis sakis is offline
Registered User
 
Join Date: Nov 2009
Posts: 19
Select a field if mathes to 2 or more criteria

Hi

I have this db table

prod_id cat_id
1---------1
2---------1
3---------1
1---------2

I want the query to search for a product that belongs to 2 categories (having the cat_id's). In this case search for products that belongs to cat_id's 1 and 2.

in this example is prod_id=1 (belongs both to 1 and 2).

Is this possible to be done with a query ??

Plz help
Reply With Quote
  #2 (permalink)  
Old 11-17-09, 11:05
dav1mo dav1mo is offline
Registered User
 
Join Date: Dec 2007
Location: Richmond, VA
Posts: 782
Code:
select a.prod_id
   from ur_table a
where exists (select 1 from ur_table b
                   where a.prod_id <> b.prod_id
                       and a.cat_id = b.cat_id)
Dave
Reply With Quote
  #3 (permalink)  
Old 11-17-09, 11:36
mike_bike_kite mike_bike_kite is offline
vaguely human
 
Join Date: Jun 2007
Location: London
Posts: 2,519
I'm not sure the previous query will work (apologies if it does). Anyway something like the following might work better and be easier to expand if you need to match against 3 categories etc:
Code:
select   prod_id
from     ur_table
where    cat_id in ( 1,2 )
group by prod_id
having   count( distinct cat_id ) = 2;
Mike
Reply With Quote
  #4 (permalink)  
Old 11-17-09, 16:45
sakis sakis is offline
Registered User
 
Join Date: Nov 2009
Posts: 19
Thanks a lot guys
I used Mike's solution and it works !!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On