一起加入两个mysql查询

时间:2012-04-07 15:06:31

标签: php 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;
}

1 个答案:

答案 0 :(得分:1)

将它们与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')");