问题
Here are my tables :
select * from user
USERID NAME STATUS
1 AAA Member
2 BBB Member
3 CCC Supervisor
4 DDD Member
5 EEE Member
select * from attendance
NO DATE SUPERVISOR MEMBER
1 2019-12-11 3 1
2 2019-12-11 3 2
3 2019-12-11 3 4
4 2019-12-11 3 5
select * from detail
NO USERID ATTENDANCE REASON
1 1 0 SICK
2 2 1 -
3 4 1 -
4 5 1 -
The result I want :
USERID DATE NAME REASON SUPERVISOR
1 2019-12-11 AAA SICK CCC
2 2019-12-11 BBB - CCC
3 2019-12-11 DDD - CCC
4 2019-12-11 EEE - CCC
The SQL I've tried calls the supervisor's userid instead of the name of the supervisor.
SELECT d.userid, a.date, u.name, d.reason, a.supervisor FROM attendance a INNER JOIN detail d on a.userid = d.userid INNER JOIN user u on d.userid = u.userid WHERE d.attendance=0
I need help with the sql to call the supervisor's name not the userid. Thanks..
回答1:
You have to join the user table twice because you are matching it for both the member name and the supervisor name. I also used LEFT JOIN because sometimes the reason does not have a value but you still want to pull the records from the other tables.
SELECT u1.userid, a.date, u1.name, d.reason, u2.name AS supervisor
FROM user u1
LEFT JOIN attendance a ON u1.userid = a.member
LEFT JOIN detail d ON u1.userid = d.userid
LEFT JOIN user u2 ON a.supervisor = u2.userid
WHERE d.attendance = 0
回答2:
SELECT u1.userid, a.date, u1.name As Name, d.reason, u2.name AS supervisor
FROM user u1
LEFT JOIN attendance a ON u1.userid = a.member
LEFT JOIN detail d ON u1.userid = d.userid
LEFT JOIN user u2 ON a.supervisor = u2.userid
WHERE d.attendance=0;
来源:https://stackoverflow.com/questions/59282376/how-to-get-the-supervisors-name-instead-of-the-userid-inner-join-in-mysql