2012-04-09 29 views
-1

我有2個表(表1,表2)表1具有字段id和表2具有表1中引用的ID字段爲外鍵字段id_eid。sql:我如何執行兩個依賴項查詢?

我從表1從它匹配一個determinated條件,然後如果這些數據在表2中引用刪除數據太行全部刪除。

我做這樣的事情,假設con是Connection對象,並自動提交設置爲在其假。

String query1 = "delete from table2 where exists 
(select * from table1 where someparameter = ? and table1.id = table2.id_eid)" 

然後我使用PreparedStatement執行第一個查詢1。

然後我有

String query2 = "delete from table1 where someparameter = ? 
and exists (select * from table2 where table1.id = table2.id_eid)" 

和我與另一PreparedStatment執行這一點。

末我有con.commit()

這不起作用,則使用自動提交虛假的兩個查詢被執行了一起,但它不是,第二個查詢刪除任何行我就在想,我怎麼能做到這一點?

一個重要的注意,而不是在表1中的所有行具有表2中所引用的行。

感謝

+1

你爲什麼不解決您的SQL表定義?您可以在表2上使用外鍵,因此如果從表1中刪除某些內容,數據庫將刪除表2上的相關條目。 – tartar 2012-04-09 20:20:08

+1

@tartar你的意思是改變表添加一個ON DELETE CASCADE?我已經無法修改表 – res1 2012-04-09 20:28:14

+0

當你刪除表1上的ID的項目,第二個查詢的第二部分是否會持有? (select * from table2 where table1.id = table2.id_eid)「 – tartar 2012-04-09 20:34:00

回答

1

你總是可以查詢數據刪除第一,然後第二刪除:

1)Select ID from table1 where <criteria>

2)Select ID from table2 where <criteria>

3)Delete from table1 where ID in <results from (1)>

4)Delete from table2 where ID in <results from (2)>

0

如果 「必須從表1匹配determinated條件的所有行刪除」 我覺得字符串QUERY2必須

String query2 = "delete from table1 where someparameter = ?"