如果不存在则插入 MySQL
Insert into if not exist MySQL
我正在使用 PostgreSQL 获取数据,我想将其插入 MySQL。我有一个 php 脚本,它允许我获取数据,检查是否重复,然后将其插入 MySQL 数据库。问题是,它不是仅插入不存在的数据,而是插入一个随机行并且不插入任何其他数据。
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
变量$episode_col
和$episode_values
通过内爆从名为$episode
的数组中获取数据:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
这是你的代码。
IF
语句用于比较,你的只是获取数组,你的 IF
语句中没有条件。您需要修复语句以获取列及其各自的值。
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
您也可以尝试使用 WHERE EXISTS
或 WHERE NOT EXISTS
。
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
更多信息:https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html
我正在使用 PostgreSQL 获取数据,我想将其插入 MySQL。我有一个 php 脚本,它允许我获取数据,检查是否重复,然后将其插入 MySQL 数据库。问题是,它不是仅插入不存在的数据,而是插入一个随机行并且不插入任何其他数据。
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
变量$episode_col
和$episode_values
通过内爆从名为$episode
的数组中获取数据:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
这是你的代码。
IF
语句用于比较,你的只是获取数组,你的 IF
语句中没有条件。您需要修复语句以获取列及其各自的值。
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
您也可以尝试使用 WHERE EXISTS
或 WHERE NOT EXISTS
。
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
更多信息:https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html