Stack Overflow
Stack Overflow

Reputation: 247

Combine the results of two SQL queries

How can I combine the results of these two sql queries either in SQL or PHP .. they're all involving joins .. I would like to combine them both and sort them by orderid .. how can I do that ?

first query

$sqlstr = "SELECT op.* FROM products_to_products_extra_fields AS p 
    INNER JOIN orders_roster AS r ON p.products_id = r.products_id 
    INNER JOIN orders_products AS op ON r.orders_id = op.orders_id
    INNER JOIN orders AS o on op.orders_id = o.orders_id
    WHERE p.products_extra_fields_id = 14
      AND p.products_extra_fields_value between '" 
         . tep_db_input($startdate) . "' and '" 
         . tep_db_input($enddate) . " 23:59:59'
      AND r.roster_status != 'Removed'
      AND o.payment_method = 'Institutional Billing'
      AND o.orders_status < 100001
    GROUP BY o.orders_id
    ORDER BY DECODE(o.cc_type, '$salt') ASC";  

SECOND query

$sqlstr2 = "SELECT op.* FROM products_to_products_extra_fields AS p 
    INNER JOIN orders_products AS op ON p.products_id = op.products_id 
    INNER JOIN orders AS o on op.orders_id = o.orders_id
    WHERE p.products_id IN 
      (SELECT products_id 
        FROM products_to_products_extra_fields 
        WHERE p.products_id NOT IN 
          (SELECT products_id 
           FROM products_to_products_extra_fields 
           WHERE products_extra_fields_id = 14)
      )
      AND o.date_purchased between '" 
         . tep_db_input($startdate) . "' and '" 
         . tep_db_input($enddate) . " 23:59:59'
      AND o.payment_method = 'Institutional Billing'
      AND o.orders_status < 100001
    GROUP BY o.orders_id
    ORDER BY DECODE(o.cc_type, '$salt') ASC";  

Upvotes: 0

Views: 2359

Answers (2)

Joseph Lust
Joseph Lust

Reputation: 19985

Just make a UNION query and get the results merged on the SQL side. No PHP needed.

Upvotes: 2

JustinM151
JustinM151

Reputation: 744

If you need them combined on the PHP end, I am going to assume you are left with an array of arrays (MySQL Rows), which you could simply loop through both sets of results and use array_push to push them into 3rd(complete) array. You could also toy around with array_merge but sometimes with multidimensional arrays the end result isnt what you expected.

https://www.php.net/manual/en/function.array-push.php https://www.php.net/function.array-merge

Upvotes: 2

Related Questions