Skip to content
Advertisement

Join and flatten table output

I am currently trying to join 3 tables. The main table is company, if there is 3 companies and 2 roles exists in the role table I want the output to be like this:

For each role there must be a row for a company. If no user is linked to a role and company then it should just show: Companyname, Rolename, null

Database schema:

Test data script:

Attempt:

Please advise what approach I can use to achieve this

Advertisement

Answer

Given you don’t have a relationship between a Role and a Company, I assume you want every combination of Role/Company, which is where you use a CROSS JOIN.

Then you would LEFT JOIN your User table on since you want to return null if a user doesn’t exist for a given Company-Role.

Note the use of shorter aliases for clarity.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement