-
MySQL教程之mysql的一个坑。修改或者删除的时候不
在mysql的语法中。修改或者删除的时候不能直接调用子查询的结果集。需要先给子查询其别名。在调用。
比如:下面的去除重复项
DELETE FROM t_equipment_type t WHERE t.type = 2
AND (t.type_code,t.type_name) IN (
SELECT type_code,type_name FROM t_equipment_type
GROUP BY type_code, type_name HAVING COUNT(*) > 1)
AND t.rec_id NOT IN (
SELECT MIN(rec_id) FROM t_equipment_type
GROUP BY type_code, type_name HAVING COUNT(*) > 1)
这样会报错。
正确的写法如下:
DELETE FROM t_equipment_type WHERE rec_id IN (
SELECT b.* FROM (
SELECT rec_id FROM t_equipment_type WHERE
type_code IN (
SELECT type_code FROM t_equipment_type WHERE TYPE = 2
GROUP BY type_code HAVING COUNT(*) > 1)
AND rec_id NOT IN (
SELECT MIN(rec_id) rec_id FROM t_equipment_type WHERE TYPE = 2
GROUP BY type_code,type_name HAVING COUNT(*) > 1)
) b )