UNION ALL与INNER JOIN一起使用

问题描述

我正在尝试使用UNION ALL连接3个表。我尝试了以下代码。并给出以下错误的参数编号错误:绑定变量的数量与令牌的数量不匹配。

$codeArray = explode(',',$code);
$inQuery = implode(',array_fill(0,count($codeArray),'?'));    
$full_dt = date('Y-m-d H:i:s');
$query =  "SELECT * FROM
                 (
                    SELECT
                       a.*
                    FROM pat_info a 
                       INNER JOIN
                          pat_medication b 
                          ON a.id = b.pat_id 
                    WHERE
                      a.status != 2 AND b.status != 2 
                      AND '$full_dt' BETWEEN b.start_date AND b.end_date 
                      AND a.location_code IN ($inQuery)
                      AND b.stock_status != '2' 
                      AND (b.total_qty - (b.given + b.not_taken)) < 12 
                   UNION ALL
                   SELECT
                   a.*
                FROM pat_info a 
                   INNER JOIN
                      prn_medication b 
                      ON a.id = b.pat_id 
                WHERE
                  a.status != 2 AND b.status != 2 
                  AND '$full_dt' BETWEEN b.start_date AND b.end_date 
                  AND a.location_code IN ($inQuery)
                  AND b.stock_status != '2' 
                  AND (b.total_qty - (b.given + b.not_taken)) < 12 
               ) x 
               GROUP BY a.id ORDER BY a.id DESC";
$statement = $con->prepare($query);
$statement->execute($codeArray);

解决方法

由于两次在代码中使用了in子句,因此需要将值绑定两次。

一种简单的方法是在execute() ...

之前复制数据。
$codeArray = array_merge($codeArray,$codeArray);

您还需要更改

GROUP BY a.id ORDER BY a.id DESC

GROUP BY x.id ORDER BY x.id DESC

作为a别名位于子选择中,而不是整个SELECT。