开发者

SQL Join queries with multiple tables

I have a database with the following layout:

employees (person_name, street, city) 
works (person_name, company_name, salary) 
companies (company_name, city) 
manages (person_name, manager_name)

I need to come up with a query that will allow me to find all employees who are ear开发者_JS百科ning more then their managers. I know this involves some pretty intense JOINing between the employees, works, and manages tables, and I can't quite get one that will work. Can someone help me out, and explain how the solution is obtained?


First off, name isn't a great key.

The key to the answer is you can join to a table more than once (remember to alias your tables so you can distinguish which one you want to reference).

Without writing the query for you it means you should select Employees, join through Works and Companies (this gives you employee salary). This should be joined through Manages which joins back to Employees to get your manager details. This version of Employees can be joined to Works for the second time to get your manager salary. Then just compare the salaries in your WHERE clause.


SELECT w.person_name
FROM works w 
    INNER JOIN manages m
        ON m.person_name = w.person_name
            INNER JOIN works wManager
                ON wManager.person_name = m.manager_name
WHERE w.salary > wManager.salary
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜