请帮我解决这个问题。我试图删除表中与数组中的数据不匹配的SQL行。
SQL表:
| id | Name | No
------------------
| 1 | john | 14
| 2 | rui | 156
| 3 | ted | 148
| 4 | alex | 123
| 5 | depay | 56
阵列:
Array
(
[0] => Array
(
[name] => john
[no] => 14
)
[1] => Array
(
[name] => ted
[no] => 148
)
[2] => Array
(
[name] => depay
[no] => 56
)
)
答案 0 :(得分:0)
这可能对您有所帮助
[akshay@localhost tmp]$ cat test.php
<?php
$array = array (
array (
'name' => 'john',
'no' => '14'
),
array (
'name' => 'ted',
'no' => '148'
),
array (
'name' => 'depay',
'no' => '56'
)
);
$table = "some_table";
$sql = "DELETE FROM ".$table." WHERE (NAME,NO) NOT IN (". implode(",",array_map(function($_){ return sprintf("('%s',%d)",$_['name'],$_['no']);},$array)).")";
print $sql."\n";
?>
<强> 输出 强>
[akshay@localhost tmp]$ php test.php
DELETE FROM some_table WHERE (NAME,NO) NOT IN (('john',14),('ted',148),('depay',56))
答案 1 :(得分:0)
如果你可以返回&#34; id&#34;那将会容易得多。也称为数组的表的主键。在这种情况下,您可以抓住那些ID,并在删除操作期间排除等式中的那些。
$selectQ = 'select id from table_name'; // and no>10
$result = mysql_result($selectQ);
$ids = array();
while ($info = mysql_fetch_assoc($result)) {
$ids[] = $info['id'];
}
if($ids) {
$deleteQ = 'delete from table_name where id not in ('.implode(",", array_values($ids)).')';
mysql_query($deleteQ);
}
P.S:在选择查询期间,请确保包含用于查找这些用户的逻辑。例如,谁&#34; no&#34;大于X.否则,默认情况下,此查询将返回所有ID,最终不会删除任何内容。