我在DB,A和B中有两个表。每个表只包含一列,即电子邮件。所以我想检查表B中的每个电子邮件对表A,如果存在,删除它;如果它不存在,请添加它。
我该怎么做?
答案 0 :(得分:1)
理想情况下,你应该在纯SQL中真正做到这一点,而不必使用php。
我们假设您的表格A包含列a integer
,而表格B包含列b integer
。然后你可以做这样的事情:
create temporary table X as select a from A join B on A.a=B.b;
delete from B where b in (select a from X);
delete from A where a in (select a from X);
insert into A (a) (select b from B);
执行以下操作:
当表X创建为临时表时,它将在数据库连接关闭时自动删除。
现在,如果您需要从PHP调用它,您可以执行以下操作:
$db = new PDO($CONNECT_STRING, USERNAME, PASSWORD);
$db->exec("create temporary table X as select a from A join B on A.a=B.b");
$db->exec("delete from B where b in (select a from X)");
$db->exec("delete from A where a in (select a from X)");
$db->exec("insert into A (select b from B)");
$db = null;
修改强>
如果你需要的只是B中A中不存在的记录,那么你可以这样做一个简单的SQL:
select b from B where b not in (select a from A)