Jason
Jason

Reputation: 1

How can I combine 2 SQL queries on the same column in the same table?

I need to combine 2 queries into one. Both query the same table and same column name. I need the results in one query so that I can repeat region the results. I have tried UNION but this doesn't run the second half correctly. Query 1 is as follows:

   SELECT o.value AS sdate
    FROM order_option o
        INNER JOIN order_product p ON o.order_product_id = p.order_product_id 
    WHERE 
        p.product_id = '$_GET[u]'
        AND o.name = 'Start Date'

And query 2 is as follows...

SELECT o2.value AS sday
    FROM order_option o2
        INNER JOIN order_product p ON o2.order_product_id = p.order_product_id 
    WHERE 
        p.product_id = '$_GET[u]'
        AND o2.name = 'Number of Days'

Upvotes: 0

Views: 357

Answers (2)

a'r
a'r

Reputation: 36999

You can use a combination of MAX and CASE like this

SELECT 
    MAX(CASE WHEN o.name = 'Start Date' THEN o.value END) AS sdate,
    MAX(CASE WHEN o.name = 'Number of Days' THEN o.value END) AS sday
FROM order_option o
    INNER JOIN order_product p USING (order_product_id)
WHERE 
    p.product_id = '$_GET[u]'
;

Upvotes: 0

Randy
Randy

Reputation: 16677

UNION should be correct. Does the second query run correctly as shown? if so, it should run the same way in a UNION. You may try UNION ALL and see if that 'corrects' the query.

Upvotes: 1

Related Questions