如何删除表1中不存在的行

时间:2013-04-26 04:05:16

标签: mysql sql

嘿伙计们需要你的帮助我很多尝试,现在我很累,找不到出路。

我有两张桌子和一张桌子。我做内连接想要删除表2中没有外来id的那些行,下面我已经提到了结构..

表1

     Column A(Foreign)     Column B  

     record A              Some thing
     record B              Some thing
     record c              Some thing

表2

     Column A(Foreign)     Column B  

     record A              Some thing
     record B              Some thing

现在实际上我想要删除不在表2中的记录C.有没有出路???

3 个答案:

答案 0 :(得分:1)

DELETE FROM `Table 1` t1
WHERE NOT EXISTS (
    SELECT 1 FROM `Table 2` t2
    WHERE t2.`Column A(Foreign)` = t1.`Column A(Foreign)`
)

顺便说一句可怕的表名和列名

在这里演示 - http://sqlfiddle.com/#!2/4c2d8/1

答案 1 :(得分:0)

这有效:

DELETE VM.* FROM `Table1` AS VM
LEFT JOIN `Table2` AS VL
ON VL.`Column A(Foreign)` = VM.`Column A(Foreign)d`
WHERE VL.`Column A(Foreign)` IS NULL

答案 2 :(得分:-1)

试试这个,工作。

http://sqlfiddle.com/#!2/d5f02/1

create table t1 (
  a varchar(16),
  b varchar(16)
);

create table t2 (
  a varchar(16),
  b varchar(16)
);

insert into t1 values
('record A', 'Some thing'),
('record B', 'Some thing'),
('record c', 'Some thing');

insert into t2 values
('record A', 'Some thing'),
('record B', 'Some thing');

delete t1
FROM  t1 left outer join t2 
ON t1.a = t2.a
where t2.a is null