UNION ALL 与 INNER JOIN 一起使用

UNION ALL use with 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 别名在 sub-select 而不是整体 SELECT。