J
J
Jake Taylor2021-08-21 14:42:53
SQL
Jake Taylor, 2021-08-21 14:42:53

How to use INNER JOIR on two tables based on 3rd table?

There are 3 tables in the database.
Companies - contains information about existing companies.
Accounts - contains account information.
Employees - links the Companies and Accounts tables saying that a certain employee works for a certain company.
6120e3a530db7001746831.png

I have an Employee object stored in the session, which contains the employee_id, company id and current user account id fields.
Next , I want to create a stored procedure that accepts employee_id, which will find the company_id link from the Employees table; account_id and will display all columns from the Companies and Accounts tables for the given user.

How to extract information about the user and his company using JOIN (INNER JOIN)?

Here's what came to mind:

SELECT company_name, account_first_name, account_last_name, account_login
FROM accounts
INNER JOIN companies ON company_id = 21 AND account_id = 28;
...

The result is the same, but how is it to combine the two queries below into one:
SELECT account_id, company_id
FROM employees
WHERE employee_id = 3;
// результат company_id = 21, account_id = 28

SELECT company_name, account_first_name, account_last_name, account_login
FROM accounts
INNER JOIN companies ON company_id = 21 AND account_id = 28;


How to make a query with JOIN, when there are 2 ads from the employee table, to get all the fields of the company and the corresponding account?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vilinyh, 2021-08-21
@n199a

SELECT ...
FROM table1 t1
INNER JOIN table2 t2 on ...
INNER JOIN table3 t3 on ...
...
INNER JOIN tableN tN on ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question