我有两个表tmp_table、test_contacts。 tmp_table 是根据 csv 上传创建的。有时,在 csv 上传中,我们的 test_contacts 表中已经有一封电子邮件。这是我必须比较更新/插入的代码。 IF 语句执行正常,但 ELSE 内的 mysql_query 不起作用。
$query = "SELECT id FROM test_contacts ORDER BY id DESC LIMIT 1";
$result = mysql_query($query, $conn);
while($rows=mysql_fetch_assoc($result)){
echo $rows['id'];
$duplicate = mysql_query("SELECT test_contacts.email, tmp_table.email FROM test_contacts, tmp_table WHERE test_contacts.email = tmp_table.email");
if (mysql_num_rows($duplicate) > 0) {
mysql_query("UPDATE test_contacts, tmp_table SET test_contacts.accountnum = tmp_table.accountnum, test_contacts.type=tmp_table.type, test_contacts.rep=tmp_table.rep, test_contacts.lname=tmp_table.lname, test_contacts.fname=tmp_table.fname WHERE test_contacts.email=tmp_table.email");
} else {
mysql_query("INSERT INTO test_contacts (account,source,accountnum,tags,type,rep,lname,fname,title,company,address,addresstwo,city,state,zip,email,cell,officenum,email_status,date,country) SELECT tmp_table.account,tmp_table.source,tmp_table.accountnum,tmp_table.tags,tmp_table.type,tmp_table.rep,tmp_table.lname,tmp_table.fname,tmp_table.title,tmp_table.company,tmp_table.address,tmp_table.addresstwo,tmp_table.city,tmp_table.state,tmp_table.zip,tmp_table.email,tmp_table.cell,tmp_table.officenum,tmp_table.email_status,tmp_table.date,tmp_table.country FROM tmp_table");
}
echo "<h2>Contacts Uploaded</h2>";
mysql_query ('TRUNCATE TABLE tmp_table;');
mysql_close($conn);
最佳答案
您想要做的事情可能可以通过ON DUPLICATE KEY UPDATE
更好地完成。为此,您需要识别指定重复项的列。在本例中,我认为是电子邮件
。因此,您需要声明 email 作为表的主键或具有唯一索引。
然后插入
代码看起来像这样:
INSERT INTO test_contacts(account, source, accountnum, tags, type, rep, lname, fname, title,
company, address, addresstwo, city, state, zip, email, cell, officenum,
email_status, date, country
)
SELECT tt.account, tt.source, tt.accountnum, tt.tags, tt.type, tt.rep, tt.lname,
tt.fname, tt.title, tt.company,tmp_table.address, tt.addresstwo, tt.city, tt.state,
tt.zip, tt.email, tt.cell, tt.officenum, tt.email_status, tt.date, tt.country
FROM tmp_table tt
ON DUPLICATE KEY UPDATE account = VALUES(account),
. . .
country = VALUES(country);
您可以填写。 。 .
以及要分配的其余列。
关于php - 比较两个表如果重复列则更新,如果不匹配则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568755/