[英]sql query to delete parent table rows which are not used in child table
我的問題標題正好說我想要幫助。
表定義和關系:
我在下面的查詢中嘗試了此操作,但未從Measurement_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;
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;
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上檢查一下。
這里的問題-你使用INNER JOIN,所以你甚至不選擇measuremnt_id
不存在,做food_units_relation
。 而是使用RIGHT JOIN並排除t1
表的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.