Jump to content

Help with JOIN


zeep25

Recommended Posts

I have three tables like this:

 

subjects

+-----------+-----------+
| SubjectID |   Name    |
+-----------+-----------+
|       50  |   English |
|       51  |   Math    |
|       52  |   History |
|       53  |   Arts    |
|       54  |   Music   |
+-----------+-----------+

 

grades

+---------+--------------+
| GradeID |     Name     |
+---------+--------------+
|     10  |   Tenth      |
|     11  |   Eleventh   |
|     12  |   Twelfth    |
|     13  |   College    |
|     14  |   HomeSchool |
+---------+--------------+

 

 

products

+-----------+-----------+----------+--------------+
| ProductID | SubjectID | GradeID  |    Name      |
+-----------+-----------+----------+--------------+
|     84512 |    50,53  | 10,11,12 |   Product 1  |
|     84513 | 54,50,51  |    11,12 |   Product 2  |
|     84514 |    53,51  | 14,12,13 |   Product 3  |
+-----------+-----------+----------+--------------+

 

As you can see, each product has multiple subjects and grades associated with it. The way I am getting the required info for each product. I am doing three queries like this:

 

SELECT 
* 
FROM 
products 
WHERE 
ProductID='84512'

then the use the result from that to do this:

SELECT 
* 
FROM 	
subjects 
WHERE 
FIND_IN_SET(SubjectID, '50,53')

and then finally get the grade levels for the product 84512

SELECT 
* 
FROM 	
grades 
WHERE 
FIND_IN_SET(GradeID, '10,11,12')

 

Now I wanted to know can i use JOIN or WHERE to get all the data (the two different subject names, and the three different grade levels) in one query?

 

Info:

Processor: 4 x Xeon 3 Ghz

OS: RedHat Linux

Memory : 2 GB

Mysql: 4.1.22-standard

Link to comment
Share on other sites

This is a fun query to create:

SELECT
ProductID
, group_concat(DISTINCT subjects.Name SEPARATOR '\n') AS subject_names
, group_concat(DISTINCT grades.Name SEPARATOR '\n') AS grade_names
, products.Name
FROM products
INNER JOIN subjects ON find_in_set(subjects.SubjectID, products.SubjectID)
INNER JOIN grades ON find_in_set(grades.GradeID, products.GradeID)
WHERE ProductID = 84512
GROUP BY ProductID

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.