两个mysql查询和2个$结果。只使用一个mysql查询,我可以获得相同的2 $结果吗?

时间:2013-12-22 09:34:10

标签: php mysql

有html输入(用户以html格式输入),如此

row_id | debit  | credit |
---------------------------
1      |2610    | 2380
2      |2620    | 2310
3      |5310    | 2621

有这样的mysql表

TrackPayments | AccountNumber
---------------------------
1             |2610    
1             |2310   
0             |2380   
1             |2620    
1             |2621    
1             |5310

希望为每个TrackPaymentsdebit

获取列credit的值

首先创建数组$debit$credit,如下所示:

 foreach ($_POST['row_id'] as $i => $row_id) {
 $debit[] = $_POST['debit'][$i];
 }

 foreach ($_POST['row_id'] as $i => $row_id) {
 $credit[] = $_POST['credit'][$i];
 }

然后执行2次查询

 $stmt1 = $db->prepare('SELECT TrackPayments FROM users WHERE AccountNumber= ?');
 $stmt1->execute( $debit );
 $result1 = $stmt1->fetch(PDO::FETCH_ASSOC);

 $stmt2 = $db->prepare('SELECT TrackPayments FROM users WHERE AccountNumber= ?');
 $stm2->execute( $credit );
 $result2 = $stmt1->fetch(PDO::FETCH_ASSOC);

得到

$result1 = array("1", "1", "1");

$result2 = array("0", "1", "1");

代码很长,我做2个mysql查询。是否可以使用一个mysql查询获得相同的结果(使用较少的系统资源)?

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情

SELECT debit, u.TrackPayments track_debit,
       credit, u2.TrackPayments track_credit
  FROM
(
  SELECT 2610 debit, 2380 credit UNION ALL
  SELECT 2620, 2310 UNION ALL
  SELECT 5310, 2621 
) q JOIN users u
    ON q.debit = u.AccountNumber JOIN users u2
    ON q.credit = u2.AccountNumber

示例输出:

| DEBIT | TRACK_DEBIT | CREDIT | TRACK_CREDIT |
|-------|-------------|--------|--------------|
|  2620 |           1 |   2310 |            1 |
|  2610 |           1 |   2380 |            0 |
|  5310 |           1 |   2621 |            1 |

SELECT AccountNumber, TrackPayments, 'debit' type
  FROM users
 WHERE AccountNumber IN(2610, 2620, 5310)
 UNION ALL
SELECT AccountNumber, TrackPayments, 'credit' type
  FROM users
 WHERE AccountNumber IN(2380, 2310, 2621);

示例输出:

| ACCOUNTNUMBER | TRACKPAYMENTS |   TYPE |
|---------------|---------------|--------|
|          2610 |             1 |  debit |
|          2620 |             1 |  debit |
|          5310 |             1 |  debit |
|          2310 |             1 | credit |
|          2380 |             0 | credit |
|          2621 |             1 | credit |

这是 SQLFiddle 演示