0

i want to join 2 mysql tables .but join information is in a separate table .let's say i have 3 table named student ,course and reg contain id of student and course he does.

student table

    s_id | name
    1    | miki    
    2    | foly    
    3    | oski  



course table    
        c_id | name
        101  | c++    
        102  | java    
        103  | ruby 


reg  table

    s_id | c_id
    1    | 101    
    1    | 102    
    2    | 101 

now i want to get all the course someone do.i wrote sql query for that without using join query .but i want to do same thing using join query .this is my query

SELECT c.name FROM student as s,course as c,reg as r where r.s_id=s.s_id and r.c_id=c.c_id and s.name='miki';
1
  • show us your query and expected result Aug 23, 2014 at 17:38

4 Answers 4

2

Statement

SELECT c.name
FROM student as s,couse as c,reg as r 
where r.s_id=s.s_id and r.c_id=c.c_id and s.name='miki'

is join too, , between table names is short cut for cross join, so you already using joins (actually you have some conditions in where, so RDBMS will optimize it to inner join)

but, of course you can rewrite it to different syntax:

SELECT c.name
FROM couse as c
inner join
reg as r 
on (c.c_id = r.c_id and r.s_id=(select s_id from student where name='miki'));

another syntax:

SELECT c.name
FROM couse as c
inner join
reg as r 
on (c.c_id = r.c_id)
inner join
student as s
on (r.s_id=s.s_id and s.name='miki');

and another one:

SELECT c.name
FROM couse as c
inner join
reg as r 
on (c.c_id = r.c_id)
inner join
student as s
on (r.s_id=s.s_id)
where s.name='miki';

depending on bunch of conditions performance of these 4 queries can be different, but results will be the same

2

Just join all 3 tables to get the result

select c.name
from course c
join reg r on r.c_id = c.c_id
join student s on s.s_id = r.s_id
where s.name = 'miki'
2
SELECT s.name,
  c.name
FROM student s
JOIN reg r
ON r.s_id = s.s_id
JOIN course c
ON c.c_id = r.c_id
WHERE s.name = "miki"
0
SELECT c.name, s.name as stud FROM course c
JOIN reg r on c.c_id = r.c_id 
JOIN student s on r.s_id = s.s_id 
WHERE s.name = 'miki'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.