2013-08-26 49 views
2

我想从数据表中删除多条记录。问题是,如果我需要删除3个存款记录,我不仅需要查找“存款”关键字,还需要查找“余额”关键字。MySQL - 嵌套在条件下

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.")"; 

任何欢迎指导。

回答

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)); 
+0

对不起,默默无闻。我更新了我的问题。 'action_id'是非唯一的标识符。 – mintaras

+0

@ user1288841更新了我的答案 –

+0

它似乎工作正常。谢谢。 – mintaras