如何实现删除中间表

时间:2014-09-24 07:47:12

标签: sql

在我的Java程序中,我希望实现这样一段SQL,当删除表A时,代码使用for condition,delete Table B(linkId=deleted ids of Table A)

表A:

===============================================
id          |        code      |    names     |
===============================================
1           |          A       |    name1     |
2           |          A       |    name2     |
3           |          A       |    name3     |
4           |          B       |    name4     |
5           |          B       |    name5     |
6           |          B       |    name6     |
7           |          B       |    name7     |
8           |          C       |    name8     |

表B(中间表):

================================
id          |       linkId     |...
================================
1           |          1       |...
2           |          2       |...
3           |          2       |...
4           |          2       |...
5           |          3       |...
6           |          7       |...
7           |          8       |...
8           |          8       |...
像这样:

delete from A where code = A
delete from B where linkId =(1,2,3)

如何使用sql语句实现?

2 个答案:

答案 0 :(得分:1)

如果您无法使用FOREIGN KEY选项添加ON DELETE CASCADE约束,只需更改删除顺序。

-- Delete from TableB (Remove all related records from the child table)
DELETE FROM
  TableB
WHERE
 EXISTS (SELECT 1 FROM TableA WHERE TableB.LinkId = TableA.id AND TableA.code = 'A');

-- Delete from TableA (Remove the record from the parent table)
DELETE FROM TableA WHERE code = 'A';

考虑在事务中执行与此多表deletinon相关的所有操作,以防止其中一个语句失败时数据丢失。

Transactions in MySQL

Transactions in Microsoft SQL Server (MSSQL)

Transactions in PostgreSQL

答案 1 :(得分:0)

如果B中不存在行中不存在ID的行,则可以编写

delete from B where not exists ( select 1 from A where A.id=B.linkId);

否则,您应该在从A中删除之前执行删除,以确保删除的行不会被定义丢失。