SQLite多个子查询逻辑

时间:2019-04-24 21:11:26

标签: sql sqlite

问题是要求有人编写查询以查找拥有经理的雇员的姓名(名字,姓氏),该经理在美国的某个部门工作。这里是问题的链接,以查看表https://www.w3resource.com/sqlite-exercises/sqlite-subquery-exercise-3.php

对于子查询,我对部门和位置表之间的位置id进行了左联接,然后为country_id选择了“ US”,并返回了manager_id

对于外部查询,我选择了Employee表,并从子查询列表中选择了manager_ids。

    SELECT first_name, last_name
    FROM Employees
    WHERE manager_id IN (SELECT manager_id
        FROM Departments d LEFT JOIN Locations l ON d.location_id = l.location_id
        WHERE country_id = 'US')
    ORDER BY first_name;

使用我的代码,我没有得到正确的答案,结果与网站上显示的结果集/输出相同。 正确答案中总共有三个子查询。我不明白包括涉及employees表的子查询(最外面的子查询)的目的是什么。我知道那是我搞砸的地方,但不明白为什么。

    SELECT first_name, last_name 
    FROM employees 
    WHERE manager_id IN 
       (SELECT employee_id 
        FROM employees 
        WHERE department_id IN 
           (SELECT department_id 
            FROM departments 
            WHERE location_id IN 
                (SELECT location_id 
                 FROM locations 
                 WHERE country_id='US')));

1 个答案:

答案 0 :(得分:1)

您需要联接所有表:

select e.first_name, e.last_name
from employees e 
inner join employees m on m.employee_id = e.manager_id 
inner join departments d on d.department_id = m.department_id
inner join locations l on l.location_id = d.location_id
where l.country_id='US'