将两个SQL结果合并为一个:PHP

时间:2014-01-04 15:48:53

标签: php codeigniter

我有以下疑问:

public function request_details() {//Request
        //$trans_type = 'Request';
        $sql = "SELECT distinct department.department_name , request.request_order_id , request.commodity_name , request.total_quantity_requested , request.date_added
                from request 
                INNER JOIN employee ON employee.employee_id = request.user_from 
                INNER JOIN department ON department.department_id = employee.employment_category 
                WHERE employee.employment_category != '6'
                ORDER BY (
                request.date_added
                ) DESC";
        $result = $this->db->query($sql);
        $result = $result->result_array();
        $sql1 = "SELECT * from transaction 
            INNER JOIN request ON request.request_id = transaction.request_id
            INNER JOIN employee ON employee.employee_id = request.user_from
            INNER JOIN department ON  department.department_id = employee.employment_category
            WHERE department.department_name='Pharmacy'";
        $result1 = $this->db->query($sql1);
        $result1 = $result1->result_array();
        $final_result = array_merge($result1,$result);
        return $final_result->result();
    }

我想将两个查询的结果合并为一个,我能做到的最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在查询之间使用UNION来连接

$sql = "SELECT distinct department.department_name , request.request_order_id , request.commodity_name , request.total_quantity_requested , request.date_added
        from request 
        INNER JOIN employee ON employee.employee_id = request.user_from 
        INNER JOIN department ON department.department_id = employee.employment_category 
        WHERE employee.employment_category != '6'
        ORDER BY (
        request.date_added
        ) DESC
        UNION
        SELECT * from transaction 
        INNER JOIN request ON request.request_id = transaction.request_id
        INNER JOIN employee ON employee.employee_id = request.user_from
        INNER JOIN department ON  department.department_id = employee.employment_category
        WHERE department.department_name='Pharmacy'";