Saturday, October 15, 2011

Join different tables based on field value - MySQL

Sometimes we need to join tables based on a field value of parent table. Here we have one parent table `tbluser` and two child table `tblstudent` and `tblstaff`. We need to join this and find full details of user. i don't interested to send two separate queries by checking field value of parent table first and then send second queries for fetch remaining details. I found a trick for achieve this using only one query.

select tu.username as username ,tu.user_email, tu.user_Type, ts.stud_adm_id as col1, tc.course_name as col2 from tbluser tu join
tblstudent ts on tu.username = ts.stud_id
join tblcourse tc on tc.Course_ID =ts.stud_course
union all
select tu.username as username ,tu.user_name as name, tu.user_Type,
tss.staff_id as col1, tj.job_title as col2 from tbluser tu join
tblstaff tss on tu.username = tss.staff_id
join tbljob tj on tj.job_ID =tss.staff_job

No comments:

Post a Comment