2012-04-07 142 views
0

我有以下兩個查詢,我想在一個查詢中獲得。我嘗試過,但無法實現,請你幫助我嗎?加入兩個mysql查詢在一起

感謝提前:)

查詢:1

" 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='1' AND account_code='1001') 
     OR (voucher_type='0' AND t_code='1001') 
     OR (voucher_type='0' AND account_code='1001')" 

查詢:2

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

我試了一下下,但我得到的說,我在錯誤的錯誤消息SQL語法。

$getData = $this->db->query("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='1' AND account_code='1001') 
     OR (voucher_type='0' AND t_code='1001') 
     OR (voucher_type='0' AND account_code='1001'), <<I just separated with a comma 

SELECT * FROM details 
LEFT JOIN vouchers on details.voucher_no = vouchers.voucher_no 
LEFT JOIN accounts on accounts.code = vouchers.account_code 
    WHERE (voucher_type='1' AND account_code='1001') 
     OR (voucher_type='0' AND t_code='1001') 
     OR (voucher_type='0' AND account_code='1001')"); 

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

你怎麼想加入他們嗎?你在談論一個INNER JOIN嗎?你想在哪個領域加入? – 2012-04-07 15:10:03

+0

看起來你想要一個跨細節和優惠券的外連接。您可能可以重寫爲單個查詢(例如'SELECT * FROM details,vouchers ...'),但如果沒有,則始終會有UNION ALL。 – cmbuckley 2012-04-07 15:19:40

回答

1

與UNION連他們都

$getData = $this->db->query("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='1' AND account_code='1001') 
     OR (voucher_type='0' AND t_code='1001') 
     OR (voucher_type='0' AND account_code='1001') 

UNION ALL 

SELECT * FROM details 
LEFT JOIN vouchers on details.voucher_no = vouchers.voucher_no 
LEFT JOIN accounts on accounts.code = vouchers.account_code 
    WHERE (voucher_type='1' AND account_code='1001') 
     OR (voucher_type='0' AND t_code='1001') 
     OR (voucher_type='0' AND account_code='1001')"); 
+0

謝謝Cichy :) – 2012-04-07 16:53:03