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 > relation tables and counting

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-28-05, 16:21
sgusev sgusev is offline
Registered User
 
Join Date: Dec 2005
Posts: 2
relation tables and counting

I have a table of users and a table of products, each with their own unique ids, I also have a relation table linking the user ids with each of the object ids they posess. I am trying to figure out a select call that would return a list of all products belonging to a user, with each row containing the product name (joined from the products table) and also the total number of users who have that product. Is there any way to do this with one SQL call?
Reply With Quote
  #2 (permalink)  
Old 12-28-05, 22:36
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
Code:
select p.name
     , ( select count(*)
           from userproducts
          where product_id 
              = p.id )    as product_users
  from users as u
inner
  join userproducts as up
    on up.user_id = u.id
inner
  join products as p
    on p.id = up.product_id       
 where u.id = 937   /* which user */
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 12-29-05, 14:15
sgusev sgusev is offline
Registered User
 
Join Date: Dec 2005
Posts: 2
whoa, I did not realize mySQL allowed things like that, thanks a lot for the help.
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