sql查询删除子表中未使用的父表行

时间:2014-06-05 23:10:09

标签: mysql sql

我的问题标题说明了我想要的帮助。

表定义&关系:

enter image description here


我尝试了以下查询,但它不会从measuring_units表中删除数据“jl”。我想在“measuring_units”表中删除62行,因为它没有在“food_units_relation”表中使用

我试过这个:

DELETE  t2
        FROM food_units_relation t1 JOIN measureing_units t2
        ON t1.measuring_unit_id = t2.measuremnt_id
        WHERE t1.foodUnit_relation_Id = 17 and  t2.measuremnt_id NOT IN(t1.measuring_unit_id) and t2.creater_id=1;

3 个答案:

答案 0 :(得分:0)

DELETE  t2
FROM measureing_units t2
LEFT JOIN food_units_relation t1 ON t1.measuring_unit_id = t2.measuremnt_id
WHERE t1.foodUnit_relation_Id = 17 and t1.measuring_unit_id is null and t2.creater_id = 1;

答案 1 :(得分:0)

DELETE MEASUREING_UNITS.*
FROM MEASUREING_UNITS
  LEFT JOIN FOOD_UNITS_RELATION ON MEASUREING_UNITS.MEASUREMENT_ID = FOOD_UNITS_RELATION.MEASURING_UNIT_ID
WHERE FOOD_UNITS_RELATION.FOOD_UNITS_RELATION_ID IS NULL;

SQLFiddle处查看。

答案 2 :(得分:0)

此处的问题 - 您使用INNER JOIN,因此您甚至不会选择measuremnt_id中不存在的food_units_relation。而是使用RIGHT JOIN并在t1表中排除条件IN WHERE:

DELETE  t2
        FROM food_units_relation t1 RIGHT JOIN measureing_units t2
        ON t1.measuring_unit_id = t2.measuremnt_id
        WHERE t1.measuring_unit_id IS NULL 
              AND t2.creater_id=1;

或者只使用NOT EXISTS:

   DELETE FROM measureing_units t2 
      WHERE NOT EXISTS (SELECT * FROM food_units_relation t1 
                        WHERE t1.measuring_unit_id = t2.measuremnt_id)
            AND t2.creater_id=1