根据另一个表中的值对表进行mysql查询

时间:2012-04-08 14:59:28

标签: php mysql

我有以下查询,它工作正常。如果您看到该查询,您会注意到有一个名为$code的变量,我用它来手动设置其值$code="1001";

function check1() { 

$code="1001";

 $getData = $this->db->query("SELECT * FROM vouchers 
 LEFT JOIN  details on vouchers.voucher_no = details.voucher_no 
LEFT JOIN   accounts on accounts.code = vouchers.account_code 
WHERE (voucher_type='1' AND t_code=$code)

 UNION ALL

SELECT * FROM vouchers 
LEFT JOIN details on vouchers.voucher_no = details.voucher_no 
LEFT JOIN   accounts on accounts.code = details.t_code 
 WHERE (voucher_type='0' AND account_code=$code)

 ");

       if($getData->num_rows() > 0)
        return $getData->result_array();
        else
        return null;
}

当我在视图文件中显示结果时,我使用以下脚本:

  <?php if(count($records) > 0) { ?>

  <?php $i = $this->uri->segment(3) + 0; foreach ($records as $row){ $i++; ?>

  <?php echo $row['voucher_date']; ?>  
  <?php echo $row['name']; ?> 
  <?php echo $row['amount']; ?>    <br>

<?php  } ?>

<?php } else { echo "No Record Found";} ?>

<?php 
$sum = 0;
foreach ( $records as $row ) {
 $sum += str_replace(",", "", $row['amount']);
}
?> 

  Total: <?php  echo  number_format( $sum, 2 );?>

现在我要做的是从以下mysql表中获取$code的值并获取其所有值的结果,这样当我在视图文件中显示结果时,它不会显示结果仅限$code="1001"$code="1002"$code="1003"

为了达到我想要的目标,我必须更改上面的mysql查询。但是我不明白该怎么做,请你告诉我。

提前致谢:)

表名:帐户

code   name 
1001    Cash Account
1002    Advertising Expense
1003    Accounts Receivable

1 个答案:

答案 0 :(得分:0)

SELECT * FROM vouchers 
 LEFT JOIN  details on vouchers.voucher_no = details.voucher_no 
LEFT JOIN   accounts on accounts.code = vouchers.account_code 
WHERE voucher_type='1' AND t_code IN (SELECT * FROM code_table)

 UNION ALL

SELECT * FROM vouchers 
LEFT JOIN details on vouchers.voucher_no = details.voucher_no 
LEFT JOIN   accounts on accounts.code = details.t_code 
 WHERE voucher_type='0' AND account_code IN (SELECT * FROM code_table)