我理解标题可能有点模糊,所以我会尝试用一个小例子来解释我想做什么。
我有一张叫做学生的桌子。我想从我的表中多次删除学生的所有记录。彼得和所有的记录都是如此。亚伦必须被删除。
SELECT student, count(student) AS cnt FROM `testtable` GROUP BY `student` HAVING cnt > 1
我还想删除数学为8的所有记录。
SELECT id FROM `testtable` WHERE mathematics = 8
但是我如何从这些选择查询中获取删除查询?甚至可以将2 ??
组合起来表:学生
id mathematics biology student
-- ----------- ------- -------
0 6 8 Peter
1 6 8 Peter
2 3 9 Aaron
3 8 9 Alicia
4 1 4 Peter
5 7 7 Aaron
6 6 5 Rachel
答案 0 :(得分:1)
感谢Uueerdo,他向我指出了这个方向,我让它发挥作用。
DELETE FROM testtable
WHERE mathematics =8
OR student IN (
SELECT stu
FROM (
SELECT student AS stu
FROM `testtable`
GROUP BY `student`
HAVING count( 1 ) >1
)tmp
)
答案 1 :(得分:0)
这样的东西可能会起作用(我说可能因为MySQL可能不喜欢引用子查询中的DELETE表):
DELETE FROM testable
WHERE mathematics = 8
OR student IN (
SELECT student
FROM `testtable`
GROUP BY `student`
HAVING count(1) > 1
)
;
这种方式更长,但几乎可以保证:
CREATE TEMPORARY TABLE `t`
SELECT student, count(student) AS cnt
FROM `testtable`
GROUP BY `student`
HAVING cnt > 1
;
DELETE FROM testable
WHERE mathematics = 8
OR student IN ( SELECT student FROM `t` )
;
DROP TEMPORARY TABLE `t`;
答案 2 :(得分:0)
DELETE x
FROM my_table x
JOIN my_table y
ON (y.student = x.student AND y.id <> x.id)
OR (y.id = x.id AND y.mathematics = 8);