2

我正在尝试从数据表中删除多条记录。问题是,如果我需要删除 3 条存款记录,我不仅需要查找“存款”关键字,还需要查找“余额”关键字。

TABLE Report:
--------------------------------------------------------------------------------------
| report_id   action_id   action_name   balance   received   given  item_name   total|
--------------------------------------------------------------------------------------
|    1           1        Balance           0      10        0      Gold         10  |
|    2           2        Deposit          10      10        0      Gold         20  |
|    3           3        Deposit          20      10        0      Gold         30  |
|    4           4        Balance           0       5        0      Silver        5  |
|    5           5        Deposit           5       5        0      Silver       10  |
|    6           6        Deposit          10       5        0      Silver       15  |
|    7           1        Withdraw         30       0       10      Gold         20  |
     ..        .....

我有这样一段代码:

...
// Empty array for keys (action_id, action_name)
$tempArray  = array();  

// Generates string like: '(?,"Deposit"),(?,"Deposit")'
$var = implode(',', array_fill(0,count($tempArray), '(?,"Deposit")')); 

// Generates query like: DELETE FROM Report WHERE (action_id, action_name) IN ((?,"Deposit"),(?,"Deposit")) 
$sql = "DELETE FROM Report WHERE (action_id, action_name) IN (".$var.")";

try{

$db = getConnection();
$stmt = $db->prepare($sql);
$result = $stmt->execute(array_values($tempArray));
...

我正在尝试做的事情:

...
// Generate string like: '(?,"Deposit" OR "Balance"),(?,"Deposit" OR "Balance")'
$var = implode(',', array_fill(0,count($tempArray), '(?,"Deposit" OR "Balance")')); 

// Generate query like: DELETE FROM Report WHERE (action_id, action_name) IN ((?,"Deposit" OR "Balance"),(?,"Deposit" OR "Balance")) 
$sql = "DELETE FROM Report WHERE (action_id, action_name) IN (".$var.")";

我想也许这可以工作:

...
// Generate string like: '(?,"Deposit","Balance"),(?,"Deposit","Balance")'
$var = implode(',', array_fill(0,count($tempArray), '(?,"Deposit","Balance")')); 

// Generate query like: DELETE FROM Report WHERE (action_id, action_name,action_name) IN ((?,"Deposit","Balance"),(?,"Deposit","Balance")) 
$sql = "DELETE FROM Report WHERE (action_id, action_name,action_name) IN (".$var.")";

欢迎任何指导。

4

1 回答 1

2

编辑

更新我的答案,因为现在很明显这action_id不是唯一的。

你可以像这样修改你的查询:

$var = implode(',', array_fill(0, count($tempArray), '?'));
$sql = "DELETE FROM Report WHERE action_id IN ($var) ".
       "AND action_name IN ('Deposit', 'Balance')";

$db = getConnection();
$stmt = $db->prepare($sql);
$result = $stmt->execute(array_values($tempArray));
于 2013-08-26T09:26:05.733 回答