2013-08-21 69 views
1

我想要的結果,」MySQL的子查詢問題

price1 | price2 
1. 10000 | 2. -100 
3. 20000 | 4. -200 

將要選擇的查詢,

  1. select total_price from cloud_payment where user_id='snoopy99' and demandnum= '201307-charge0000040C'

  2. select unpaid_price from gcloud.cloud_service_basic where user_id='snoopy99' and month=7

  3. select total_price from gcloud.cloud_payment where user_id='snoopy99' and demandnum= '201308-charge0000040C'

  4. select unpaid_price from gcloud.cloud_service_basic where user_id='snoopy99' and month=8

1,3-是在第一列中 2,4-是在第二列中。

任何好主意?

回答

3

嘗試。

select total_price as price from cloud_payment where user_id='snoopy99' and (demandnum= '201307-charge0000040C' OR demandnum= '201308-charge0000040C') 
UNION ALL 
select unpaid_price as price from gcloud.cloud_service_basic where user_id='snoopy99' and (month=7 OR month=8) 
0

您可以使用JOIN來選擇你的服務和支付表合併記錄,然後UNION選擇兩個這樣的記錄。事情是這樣的:

SELECT total_price, unpaid_price 
    FROM cloud_payment cp 
    JOIN gcloud.cloud_service_basic cs ON cp.user_id = cs.user_id 
    WHERE cp.user_id = 'snoopy99' 
    AND cp.demandnum = '201307-charge0000040C' 
    AND cs.month = 7 
UNION 
SELECT total_price, unpaid_price 
    FROM cloud_payment cp2 
    JOIN gcloud.cloud_service_basic cs2 ON cp2.user_id = cs2.user_id 
    WHERE cp2.user_id = 'snoopy99' 
    AND cp2.demandnum = '201308-charge0000040C' 
    AND cs2.month = 8 
; 

Example SQLFiddle.