【发布时间】:2012-01-07 00:32:23
【问题描述】:
这几天我一直在研究这个问题,并且不断遇到绊脚石。我正在尝试从 table2 中选择一个唯一的 id 并将其与 table1 中的 id 匹配。如果 id 匹配,则更新 table1 中的行并从 table2 中删除记录。如果没有匹配则将记录插入到table1中。
我已经到了可以更新记录并插入新记录的地步,但我似乎无法在插入之前删除匹配的记录,因此会创建重复记录。我在更新后尝试了删除连接查询,但因为新的 logon_id 前面有一个字符,它不再匹配 table2。
我之前为更新进行了更新连接,但我有太多查询正在进行,所以尽量保持简单。
有什么建议吗?还是这个游戏的新手。
$table2_query = "SELECT * FROM table2";
$table2_result = mysql_query($table2_query);
$table2_count = mysql_num_rows($table2_result);
if($table2_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}
while($table2_row = mysql_fetch_array($table2_result, MYSQL_ASSOC)) {
$check_number_length = strlen($table2_row['unique_id']);
if($check_number_length < 7) {
if(substr($table2_row['unique_id'], 0, 2) < 35) {
$logon_id = 'n' . $table2_row['unique_id'];
}else {
$logon_id = 'v' . $table2_row['unique_id'];
}
}else {
$logon_id = $table2_row['unique_id'];
}
// Set variables for insert query for creation of a new user record
$first_name = $table2_row['firstname'];
$last_name = $table2_row['lastname'];
$email_address = $table2_row['email'];
$duplicates_query = "SELECT * FROM table1 WHERE '$logon_id' = logon_id";
$duplicates_result = mysql_query($duplicates_query);
$duplicates_row = mysql_fetch_array($duplicates_result);
$duplicates_count = mysql_num_rows($duplicates_result);
if($duplicates_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}else {
$update_records_query = "UPDATE table1 SET first_name='$first_name', last_name='$last_name', email_address='$email_address'";
$update_records_result = mysql_query($update_records_query);
$update_records_count = mysql_affected_rows();
echo $update_records_count;
}
$create_records_query = "INSERT INTO table1 (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
$create_records_result = mysql_query($create_records_query);
$create_records_count = mysql_affected_rows();
if($create_records_count == 0){
if(mysql_error()){
echo 'Error: '.mysql_error();
}
}
echo $create_records_count . ' record(s) created.';
}
【问题讨论】:
-
请做一个“更干净”的样本。
-
那么,是什么让您无法运行该 DELETE 查询?
-
对不起@GabrielSantos 试图让它尽可能干净,但想确保一切都可以通过。我已经删除了很多无关的东西,抱歉。
-
做
if($table2_count == 0) { // SHOW ERROR }之类的事情 -
@Col.Shrapnel 更新之后,我做了一个删除连接查询,以从 table2 中删除与我刚刚插入 table1 的 id 匹配的用户,除非我执行插入时它前面有一个字符table2 中不存在,因此我找不到删除它的记录。希望这是有道理的。