'Best approach join table query
I'm new to sql. What would be the best practice for joining tables below? So far I try this UNION ALL
SELECT CONCAT(u.first_name,' ',u.middle_name,' ',u.last_name) AS student FROM users u
LEFT JOIN students s ON s.student_id= u.id
UNION ALL
SELECT CONCAT(usr.first_name,' ',usr.middle_name,' ',usr.last_name) AS faculty FROM users usr
LEFT JOIN faculty f ON f.faculty_id= usr.id
this is the results:
| student |
|---------------------|
| John Doe Garbin |
| John Faculty Samson |
| John Staff Thomas |
also the SELECT SUBQUERY but did not hit my target results, I also try this approach
SELECT CONCAT(u.first_name,' ',u.middle_name,' ',u.last_name) AS faculty, CONCAT(s.first_name,' ',s.middle_name,' ',s.last_name) AS student FROM faculty f
LEFT JOIN users AS u ON u.id = f.id
LEFT JOIN students AS s ON s.id = u.id
but the problem is alias from student is unknown. Much appreciated all answers.
users :
| id | first_name | middle_name | last_name | email | roles |
|---------|--------------|--------------|-----------|--------------------|---------|
| 1234567 | John | Doe | Garbin | [email protected] | student |
|---------|--------------|--------------|-----------|--------------------|---------|
| 7654321 | John | Faculty | Samson | [email protected] | faculty |
|---------|--------------|--------------|-----------|--------------------|---------|
| 2222222 | John | Staff | Thomas | [email protected] | faculty |
faculty:
| faculty_id | other_column |
|------------|--------------|
| 7654321 | attribute |
| 2222222 | attribute |
student:
| student_id | other_column |
|-------------|---------------|
| 1234567 | attribute |
My target results:
| student | faculty |
|-----------------|---------------------|
| John Doe Garbin | John Faculty Samson |
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
