MySQL - 嵌套在哪里条件

时间:2013-08-26 09:05:31

标签: php mysql

我正在尝试从数据表中删除多个记录。问题是,如果我需要删除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.")";

欢迎任何指导。

1 个答案:

答案 0 :(得分: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));