Hui Ting Ko
Hui Ting Ko

Reputation: 51

How can I join 4 tables using SQL to get a result

Here is a simple database schema, according to the schema, I would like to find the highest salary among all employees, presenting the information about that employee (a_id, a_name, b_area).

There will be only one result return from table D and I try to return the employment_id to link with other tables but then it returns more than 1 result. Please check my query underneath, thank you very much :) enter image description here

SELECT
     a.a_id,
     a.a_name,
     b.b_area 
FROM
     A a, B b, C c 
LEFT JOIN (SELECT d.employee_id, MAX(d.salary) FROM D d)
     ON d.employee_id= c.employee_id;

Upvotes: 0

Views: 164

Answers (5)

I think you use HAVING Clause,

SELECT a.a_id, a.a_name, b.b_area FROM A a, B b, C c LEFT JOIN D d ON c.employee_id = d.employee_id
GROUP BY d.salary
HAVING MAX(d.salary);

Upvotes: 0

Esteban P.
Esteban P.

Reputation: 2809

There are several ways:

Subselect-Solution:

 SELECT A.a_name
       ,B.b_area
       ,maxsalary.MaxSal
   FROM
      (
        SELECT D.employee_id
              ,MAX(D.Salary) as MaxSal
          FROM D
      GROUP BY D.employee
      ) maxsalary
    INNER JOIN C
            ON C.employee_id = maxsalary.employee_id
    INNER JOIN B
            ON C.b_id = B.b_id
    INNER JOIN A
            ON C.a_id = A.a_id

This solution might be more performant. As SUBSELECT maxsalary will return just one row.

Upvotes: 0

Daniel H.J.
Daniel H.J.

Reputation: 448

SELECT D.*, a.a_name, b.b_area FROM D
LEFT JOIN c ON d.employee_id = c.employee_id
LEFT JOIN a ON a.a_id = c.a_id
LEFT JOIN b ON b.b_id = c.a_id
ORDER BY D.salary DESC LIMIT 1

This will output one row as:
employee_id | salary | a_name | b_area

Upvotes: 0

Jiri Tousek
Jiri Tousek

Reputation: 12440

Start with D, then join the other tables as needed:

... D left join c on (d.employee_id = c.employee_id) left join a on ...

And the highest salary bit would be something like:

... where salary = (select max(salary) from d)

Keep in mind that this will return multiple results if there is more than one employee having the maximum salary.

Upvotes: 1

Radim Bača
Radim Bača

Reputation: 10701

You miss a join condition for your tables. This should do what you need.

SELECT a.a_id, a.a_name, b.b_area 
FROM C
JOIN A ON a.a_id = c.a_id
JOIN B ON b.b_id = c.c_id
JOIN D ON d.employee_id = c.employee_id    
WHERE d.salary = (SELECT max(salary) FROM D)

Upvotes: 0

Related Questions