0

如何简化这些步骤?php/sql 代码旨在从一个表中删除另一张表中不存在的party_id:

// party_id from one table
$array1 = array();
$db->setQuery("SELECT DISTINCT(record) FROM table1");
$contents = $db->loadObjectList();
foreach( $contents As $content ){
    $row = $content->record;
    $array1[] = $row;
}

// get party_id from different table
$array2 = array();
$db->setQuery("SELECT DISTINCT(party_id) FROM table2 WHERE user_id = '$id'");
$contents = $db->loadObjectList();
foreach ( $contents As $content ) {
    $row = $content->party_id;
    $array2[] = $row;
}

// Compare, then delete records existing in array2, but not in array1
$result = array_diff($array2, $array1);
foreach ( $result As $rslt ) {
    $db->setQuery("DELETE FROM table2 WHERE party_id = '$rslt' AND user_id = '$id'");
    $db->query();
}
4

3 回答 3

0

您是否考虑过使用子查询来删除这些记录?您可以使用该WHERE NOT EXISTS子句删除非重复行

http://docs.oracle.com/cd/E17952_01/refman-5.5-en/exists-and-not-exists-subqueries.html

于 2013-07-02T11:33:49.283 回答
0

使用不存在:

DELETE 
FROM 
  table2 AS t2 
WHERE
  NOT EXISTS (SELECT 1 FROM table1 AS t1 WHERE t1.party_id = t2.record)
AND
  t2.user_id = '$user_id';
于 2013-07-02T11:45:20.773 回答
0
DELETE FROM table2 
WHERE party_id in (SELECT DISTINCT(party_id) FROM table2 WHERE user_id = '$id')
and party_id not in (SELECT DISTINCT(record) FROM table1)
AND user_id = '$id'
于 2013-07-02T11:42:41.863 回答