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 > Complicated SELECT from multiple tables

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-07-09, 18:56
grantsewell grantsewell is offline
Registered User
 
Join Date: Mar 2009
Posts: 1
Lightbulb Complicated SELECT from multiple tables

Hi Everyone,

I'm new to the forum, looks like a great resource! Hopefully you all might be able to help me with the query I'm currently stumped on:

I have two tables, that look something like this:

Users Sample Data
-----------------------------------------
id 1
firstname John
lastname Smith
activity1 24
activity2 35

Activities Sample Data
-----------------------------------------
id 24
activityName Basketball

I basically want a query that will run and give me the following:

John Smith Basketball Baseball

I would like the query to pull the actualy activity names, instead of just the id. I know I can do this with multiple queries, but on my report that would mean I'm making possibly hundreds of queries, instead of just one. I thought maybe I could use an INNER JOIN, but I'm still pretty much a novice with advanced queries, so I'm up for any suggestions. Thanks in advance!

Cheers,

Grant
Reply With Quote
  #2 (permalink)  
Old 03-07-09, 21:26
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
the best advice i have for you is to change your table design slightly
Code:
CREATE TABLE Users
( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT
, firstname  VARCHAR(99)
, lastname   VARCHAR(99)
);
CREATE TABLE Activities
( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT
, activityName VARCHAR(99)
);
CREATE TABLE UserActivities
( usr_id INTEGER NOT NULL 
, act_id INTEGER NOT NULL 
, PRIMARY KEY ( usr_id , act_id )
);
once you see how this works, i'm sure you will agree that it is more flexible and the queries are a lot simpler

there is one row in UserActivities for each activity that every user has

a given user will be in UserActivities multiple times (once for each of his activities), and a given activity will be in UserActivities multiple times (once for each user that has that activity), but the combination of usr_id and act_id values will be unique

__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
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