简体   繁体   English

具有多个表的SQL Join查询

[英]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 earning 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. 我知道这涉及到员工,工作和管理表之间非常强烈的JOIN联接,而我还无法获得一个可以正常工作的联接。 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. 这应该通过Manages加入,Manages加入员工,以获取您的经理详细信息。 This version of Employees can be joined to Works for the second time to get your manager salary. 此版本的雇员可以第二次加入Works,以获取经理的薪水。 Then just compare the salaries in your WHERE clause. 然后,只需比较WHERE子句中的薪水即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM