black_belt
black_belt

Reputation: 6799

Joining two mysql queries together

I have the following two queries which I want to get in one query. I tried but couldn't make it happen, would you please kindly help me?

Thanks in Advance :)

Query: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')"

Query: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')"

What I tried the following but I got an error message that says I have error in SQL syntax.

 $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;
}

Upvotes: 0

Views: 185

Answers (1)

cichy
cichy

Reputation: 10634

Connect them with UNION ALL

 $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')");

Upvotes: 1

Related Questions