employee table containing empCode (fk), empName etc
role table containing roleCode (fk), roleName etc
employeeRoleMap table contains data of Many-To-Many of both (id, empCode, roleCode, isPrimaryRole etc)
One Employee can have many roles, among them only 1 primary role ( isPrimary = 1
)
To display employee details and primary role, I need to work on employee and employeeRoleMap table
So, query
select em.empCode, em.empName, em.roleCode
FROM employee em
left join employeeRoleMap erm
on (em.empCode=erm.empCode AND erm.isPrimary=1)
For which primary role is not there, it will show null. Okay.
But, now I want addition role details field like roleName.
So, I tried cross-join
select em.empCode, em.empName, em.roleCode
FROM employee em
LEFT JOIN employeeRoleMap erm
on (em.empCode=erm.empCode AND erm.isPrimary=1)
CROSS JOIN role r
WHERE em.roleCode = r.roleCode
It's working for who has roleCode, for employee having null as primary role code, those rows are getting ignored.
But, it shouldn't be the case right as employee is the left outer join even if rolecode is there or not, it should show
Instead of using CROSS JOIN , You can use LEFT JOIN
select em.empCode, em.empName, em.roleCode,r.RoleName
FROM employee em
LEFT JOIN employeeRoleMap erm
on (em.empCode=erm.empCode AND erm.isPrimary=1)
LEFT JOIN role r ON em.roleCode = r.roleCode
You could try
Select em.empCode, em.empName, em.roleCode
FROM employee em
LEFT JOIN employeeRoleMap erm
on (em.empCode=erm.empCode AND erm.isPrimary=1)
LEFT JOIN role r
on em.roleCode = r.roleCode
Without sample data it would be very difficult to know whether this would work or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.