简体   繁体   中英

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'

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.

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]'
;

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