MySQL子查询问题

时间:2013-08-21 05:38:19

标签: 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
  5. 我希望 1,3 位于第一列 2,4 位于第二列。

    有什么好主意吗?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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.