2011-06-14 62 views
1

我有一張表說table1有50條記錄,table1的記錄與其他子表使用約束綁定。刪除查詢以刪除無約束的條目

不是所有的50個記錄有約束,有可能是一些記錄(比如15)無約束的,所以我要運行刪除查詢刪除15項單獨出總50

我試過delete ignore聲明:

delete ignore from table1; 

,但它並沒有幫助&我得到這個錯誤:

Cannot delete or update a parent row: a foreign key constraint fails

什麼是最好的方式ACC在mysql查詢中忽略這個?

+0

你能簡單地刪除其中的FK爲空? – 2011-06-14 22:22:24

+0

任何示例示例? – Sharpeye500 2011-06-14 22:29:48

回答

0

DELETE FROM table1 WHERE NOT EXISTS (SELECT * FROM details_table d WHERE d.table1_id = table1.id)

+0

我有多個子表,而不是一個。 – Sharpeye500 2011-06-14 22:29:09

+0

我想你需要爲每個孩子添加「ADD NOT EXISTS」(或者使用一堆左連接)來過濾沒有子行的記錄。在這種情況下,「刪除IGNORE」似乎不起作用。我剛剛在MySQL 5.5上試了一下 - 它不顯示錯誤,但同時它也不會刪除任何行。 – a1ex07 2011-06-14 22:34:41

+0

爲了更加準確,在mysql 5.5中,''DELETE IGNORE'一旦遇到違反約束的第一行就會停止刪除行。所以一些記錄將被刪除。 – a1ex07 2011-06-14 22:39:40

0

這裏有一個簡單的,可讀的,高效的查詢,將你做它:

DELETE FROM table1 
WHERE id NOT IN (
    SELECT table1_id FROM details_table_1 
    UNION 
    SELECT table1_id FROM details_table_2 
    -- more unions to other child tables as required 
); 
0

我一直喜歡加入到使用子查詢IN()

http://dev.mysql.com/doc/refman/5.5/en/rewriting-subqueries.html

Sometimes there are other ways to test membership in a set of values than by using a subquery. Also, on some occasions, it is not only possible to rewrite a query without a subquery, but it can be more efficient to make use of some of these techniques rather than to use subqueries. One of these is the IN() construct.

.. 。

A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone. Prior to SQL-92, outer joins did not exist, so subqueries were the only way to do certain things. Today, MySQL Server and many other modern database systems offer a wide range of outer join types.

以下是如何回答與LEFT OUTER JOIN你的問題:

DELETE FROM table1 
LEFT OUTER JOIN child_table_1 c1 ON table1.id = c1.table_1_id 
LEFT OUTER JOIN child_table_2 c2 ON table1.id = c2.table_1_id 
-- More joins for additional child tables here 
WHERE c1.table_1_id IS NULL 
AND c2.table_1_id IS NULL 
-- AND other child tables 
;