MYSQL删除具有多个exeptions的行

时间:2018-03-27 14:07:55

标签: mysql node.js

在MYSQL 5.7中删除行时添加exeptions有问题。

数据表示例: 的 task_take_over

+----+---------+---------+------+------+
| ID | user_ID | task_ID | year | week |
+----+---------+---------+------+------+
| 1  | 16      | 100     | 2018 | 10   |
+----+---------+---------+------+------+
| 2  | 16      | 100     | 2018 | 11   |
+----+---------+---------+------+------+
| 3  | 16      | 100     | 2018 | 12   |
+----+---------+---------+------+------+
| 4  | 16      | 101     | 2018 | 10   |
+----+---------+---------+------+------+
| 5  | 16      | 101     | 2018 | 11   |
+----+---------+---------+------+------+
| 6  | 16      | 101     | 2018 | 12   |
+----+---------+---------+------+------+
| 7  | 16      | 102     | 2018 | 10   |
+----+---------+---------+------+------+
| 8  | 16      | 102     | 2018 | 11   |
+----+---------+---------+------+------+
| 9  | 16      | 102     | 2018 | 12   |
+----+---------+---------+------+------+

数据表示例: 的任务

+-----+-------------+---------+------------------------+
| ID  | schedule_ID | task    | preference_employee_ID |
+-----+-------------+---------+------------------------+
| 100 | 1           | thing 1 | 15                     |
+-----+-------------+---------+------------------------+
| 101 | 2           | thing 2 | 15                     |
+-----+-------------+---------+------------------------+
| 102 | 3           | thing 3 | 15                     |
+-----+-------------+---------+------------------------+

我想删除task_take_over 中的所有行,但

除外
  • JOINS任务WITH schedule_ID = 1和WHERE task.week = 12
  • 的行

所以我有以下问题:

DELETE task_take_over
FROM task_take_over
JOIN task ON task.ID = task_take_over.task_ID
WHERE task.preference_employee_ID = ?
AND task_take_over.year = ?
/* this part will be looped before executed */
AND (
    task.schedule_ID != ?
    AND task_take_over.week != ?
);

问号用[15, 2018, 1, 12]

填写

问题是没有一行具有week = 12的行将被删除。 除(task_take_over.ID = 3)外,应删除所有任务。 相反,task_take_over.ID = 3,6和9将保持未删除状态。

看起来每个task_take_over.week都会影响()之间的异常组合。只应排除schedule_ID和week组合在一起的组合。

感谢您的任何意见!

1 个答案:

答案 0 :(得分:0)

<强> Sql Demo

DELETE task_take_over
FROM task_take_over
LEFT JOIN task 
  ON task_take_over.task_ID = task.ID
 AND schedule_ID = 1 
WHERE schedule_ID IS NULL
  AND week <> 12;

<强>输出

您仍然有task_id = 100,因为这些是schedule_ID = 1 并且您仍然拥有week = 12

的行
| ID | user_ID | task_ID | year | week |
|----|---------|---------|------|------|
|  1 |      16 |     100 | 2018 |   10 |
|  2 |      16 |     100 | 2018 |   11 |
|  3 |      16 |     100 | 2018 |   12 |
|  6 |      16 |     101 | 2018 |   12 |
|  9 |      16 |     102 | 2018 |   12 |