2012-04-08 78 views
0

我有以下查詢,它工作正常。如果你看到了查詢,你會發現有一個名爲$code變量,我用手動將其值設置這樣$code="1001";基於來自另一個表的值對錶進行mysql查詢

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 

回答

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) 
相關問題