简体   繁体   中英

UNION ALL use with INNER JOIN

I am trying to join 3 tables with UNION ALL. I tried the following code. and giving this error of Invalid parameter number: number of bound variables does not match number of tokens.

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

As you have the in clause twice in your code, you need to bind the values twice.

A simple way to do this would be to duplicate the data prior to the execute() ...

$codeArray = array_merge($codeArray, $codeArray);

You also need to change

GROUP BY a.id ORDER BY a.id DESC

to

GROUP BY x.id ORDER BY x.id DESC

as the a alias is in the sub-select and not the overall SELECT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM