简体   繁体   English

使用PHP,比较两个单行MYSQL表,添加表A中表B中不存在的记录,并删除表B中不存在的记录。

[英]With PHP, compare two single-col MYSQL tables, adding records from table A that do not exist in table B, and deleting records that do

I have two tables in a DB, A and B. Each of the tables consist of just one column, email. 我在数据库中有两个表,A和B。每个表仅包含一列,即电子邮件。 So I want to check each email in table B against table A, and if it exists, delete it; 因此,我想对照表A检查表B中的每封电子邮件,如果存在,则将其删除; if it does not exist, add it. 如果不存在,请添加它。

How do I do this? 我该怎么做呢?

Ideally, you should really do this in pure SQL, without having to muck about with php. 理想情况下,您确实应该在纯SQL中执行此操作,而不必为php烦恼。

Let's say your table A has column a integer and table B has column b integer . 假设您的表A a integer ,表B的列为b integer Then you can do something like this: 然后,您可以执行以下操作:

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);

This does the following: 这将执行以下操作:

  1. Creates a temporary table and insert into it all records that exist in both A and B 创建一个临时表并将其中同时存在A和B的所有记录插入其中
  2. Deletes from B all records that exist in both tables 从B中删除两个表中存在的所有记录
  3. Deletes from A all records that exist in both tables 从A中删除两个表中存在的所有记录
  4. Insert into A everything that's remaining in B 将B中剩余的所有内容插入A

As table X is created as temporary, it will be automatically dropped when the database connection is closed. 由于表X是作为临时表创建的,因此在关闭数据库连接后将自动删除它。

Now, if you need to call this from PHP, you can do the following: 现在,如果您需要从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;

EDIT: 编辑:

If all you need is records from B that do not exist in A, then you can do a simple SQL like this: 如果您只需要B中不存在的记录,那么您可以执行以下简单的SQL:

select b from B where b not in (select a from A)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM