SQL选择至少有2个订单的员工,其中至少有一个订单位于某个区域,没有嵌套的SQL块

时间:2017-06-09 11:59:55

标签: mysql sql

我有两个表,'客户'和'员工'通过第三个表'订单'加入

| CustomerID | CDistrict |    | EmployeeID | EName |
|------------|-----------|    |------------|-------|
|      1     |     A     |    |      1     |  Alex |
|      2     |     A     |    |      2     |  Bob  |
|      3     |     B     |    |      3     |  Edd  |
|      4     |     C     |

| OrderID | CustomerID | EmployeeID |
|---------|------------|------------|
|    1    |      1     |      1     |
|    2    |      3     |      1     |
|    3    |      3     |      2     |
|    4    |      5     |      2     |
|    5    |      1     |      3     |

如何选择至少提供2个订单的所有员工的姓名,其中至少有来自区域“A”且没有嵌套SQL块的客户?也就是说,结果应该是'Alex'。

我设法使用嵌套查询执行此操作,如下所示:

SELECT EName FROM Database.Employees
WHERE 
    EmployeeID IN 
    (SELECT EmployeeID FROM Database.Orders
        GROUP BY EmployeeID
        HAVING COUNT(*) >= 2)
AND
    EmployeeID IN
    (SELECT EmployeeID FROM Database.Orders
        WHERE 
            CustomerID IN
            (SELECT CustomerID FROM Database.Customers
                WHERE CDistrict = 'A'));    

但是,我需要在没有嵌套查询的情况下执行此操作。 我选择所有至少提供2个订单的员工的查询如下:

SELECT EName FROM Database.Employees, Database.Orders
WHERE 
    Employees.EID = Orders.EID
    GROUP BY EName HAVING COUNT(OrderID) >=2
ORDER BY EName;  

我的选择是从区域'A'中选择为客户提供服务的所有员工,如下所示:

SELECT EName FROM Database.Employees, Database.Orders, Database.Customers
WHERE 
    Employees.EID = Orders.EID
    AND
    Orders.CID = Customers.CID
    AND
    CDistrict = 'A';    

但是,当我尝试将这些查询加入到像

这样的单个查询中时
SELECT EName FROM Database.Employee, Database.Orders, Database.Customers
WHERE 
    Employees.EID = Orders.EID
    AND
    Orders.CID = Customers.CID
    AND
    CDistrict = 'A'
    GROUP BY EName HAVING COUNT(OrderID) >=2;

我成了0结果。我想,这个查询可能会搜索所有在区域'A'中至少服务过2个订单的员工,但这不是我需要的 - 我需要至少服务过两个订单的员工,其中至少有一个是在'A'区。我究竟做错了什么?如何将嵌套查询转换为常规查询?

2 个答案:

答案 0 :(得分:2)

使用GROUP BYHAVING

SELECT o.EmployeeID
FROM Database.Orders o JOIN
     Database.Customers c
     ON o.CustomerId = c.CustomerId
GROUP BY o.EmployeeID
HAVING COUNT(*) >= 2 AND
       SUM(c.CDistrict = 'A') > 0;

答案 1 :(得分:1)

SELECT E.EName 
FROM Employees E INNER JOIN Orders O 
     ON O.EmployeeID=E.EmployeeID 
INNER JOIN Customers C 
     ON C.CustomerID=O.CustomerID 
WHERE C.CDistrict='A' 
GROUP BY E.EmployeeID 
HAVING COUNT(O.CustomerID) >= 2