开发者

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

开发者 https://www.devze.com 2023-03-19 10:34 出处:网络
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

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.nam开发者_JS百科e = '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]'
;
0

精彩评论

暂无评论...
验证码 换一张
取 消