sql删除基于其他表中多个字段组合的记录

时间:2014-01-15 13:21:55

标签: sql

我意识到这些表具有相同的两列,但我正在使用不灵活的约束,因此我无法更改此结构。

TableA

Host_ID | Carrier_ID 
111     |  222        /*Row 1*/
111     |  333        /*Row 2*/

表B

Host_ID | Carrier_ID      
111     |  222

如果用户尝试通过网络表单从carrier_id删除潜在客户TableA,我正在处理一个表单,该表单将触发javascript警报。

我想在delete语句中编写一个where子句,以防止删除TableATableB(在本例中为第1行)中显示的行,因为TableB存储所有的主要运营商。

允许用户通过网络表单删除第2行是完全可以的,因为Host_ID中不存在Carrier_IDTableB的组合。

2 个答案:

答案 0 :(得分:2)

这是你想要的吗?

delete from tableA
    where not exists (select 1
                      from tableB b
                      where tableA.Host_Id = b.Host_Id and tableA.Carrier_Id = b.Carrier_id
                     );

这是标准SQL,应该可以在任何数据库中使用。

编辑:

如果要删除特定值,请使用以下检查:

delete from tableA
    where Host_Id = $Host_Id and Carrier_Id = $Carrier_ID and
          not exists (select 1
                      from tableB b
                      where tableA.Host_Id = b.Host_Id and tableA.Carrier_Id = b.Carrier_id
                     );

答案 1 :(得分:0)

尝试

DELETE tablea
FROM tablea a LEFT OUTER JOIN tableb b
ON a.host_id = b.host_id
AND a.carrier_id = b.carrier_id
WHERE
b.host_id IS NULL
AND b.carrier_id IS NULL
AND a.host_id = '<<your value here>>'
AND a.carrier_id = '<<your value here>>

这使用外连接来检测tableb中是否存在匹配的行,并且当匹配的行不存在时允许删除

请参见此处的插图sql fiddler

相关问题