小编典典

删除使用多个表并在子查询中重复表

sql

我要解雇该部门所有销售量较低的员工

模式和Sql提琴

CREATE TABLE Employee
    (`ID` int, `name` varchar(6), `deptID` int);

INSERT INTO Employee
    (`ID`, `name`, `deptID`)
VALUES
    (1, 'Jhon', NULL),       (2, 'Luis', 1),
    (3, 'Angela', 1),        (4, 'Peter', NULL),
    (5, 'Sonia', 4),         (6, 'Oliver', 4);

CREATE TABLE Sales
    (`ID` int, `Sales` int);

INSERT INTO Sales
    (`ID`, `Sales`)
VALUES
    (1, 100),        (2, 300),
    (3, 500),        (4, 600),
    (5, 250),        (6, 150);

我可以做这样的事情

DELETE E 
FROM Employee E
INNER JOIN Sales S 
   ON E.`ID` = S.`ID`
WHERE `SALES` = 600;

我想要的是

DELETE E1 
FROM Employee E1
WHERE `deptID` IN (
            SELECT `deptID`
            FROM Employee E 
            Inner JOIN Sales S
               ON E.`ID` = S.`ID`
            GROUP BY `deptID`
            HAVING SUM(`Sales`) <= 400
        );

但是我不能Employee按照
手册中的 描述在内部SELECT中
使用

子查询
当前,您无法从表中删除并在子查询中从同一表中选择。

那么正确的语法是什么?


阅读 156

收藏
2021-03-17

共1个答案

小编典典

用一个 JOIN

DELETE e1
FROM Employee AS e1
JOIN (SELECT deptID
      FROM Employee AS e
      JOIN Sales AS s ON e.ID = s.ID
      GROUP BY deptID
      HAVING SUM(Sales) <= 400) AS d
ON e1.deptID = d.deptID
2021-03-17