如何将3个查询合并为1个

时间:2016-06-22 10:08:22

标签: mysql sql

SELECT `account_id`,`cust_name` 
FROM `account`
WHERE `acc_openingdate` BETWEEN '2001-01-01' AND '2016-03-31'
  AND STATUS = 'open'


SELECT `acid`,sum(amount)
FROM `payments` 
WHERE `date` BETWEEN '2001-01-01' AND '2016-03-31' 
group by `acid`

SELECT `account_id`,sum(amount)
FROM `loan` WHERE `date` BETWEEN '2001-01-01' AND '2016-03-31' 
group by `account_id`

是account_id,acid和account_id相同

2 个答案:

答案 0 :(得分:2)

您可以使用子查询;)

SELECT t1.`account_id`, t1.`cust_name`, t2.p_amount, t3.a_mount
FROM `account` t1
LEFT JOIN (
    SELECT `acid`, sum(amount) as p_amount
    FROM `payments` 
    WHERE `date` BETWEEN '2001-01-01' AND '2016-03-31' 
    group by `acid`
) t2 ON t1.`account_id` = t2.`acid`
LEFT JOIN (
    SELECT `account_id`, sum(amount) as a_mount
    FROM `loan` WHERE `date` BETWEEN '2001-01-01' AND '2016-03-31' 
    group by `account_id`
) t3 ON t1.`account_id` = t3.`account_id`
WHERE t1.`acc_openingdate` BETWEEN '2001-01-01' AND '2016-03-31'
AND t1.STATUS = 'open'

答案 1 :(得分:1)

您可以使用相关查询执行此操作:

SELECT a.account_id,a.cust_name,
       (SELECT SUM(amount) FROM payments p 
        WHERE p.date BETWEEN '2001-01-01' AND '2016-03-31' AND p.acid = a.account_id) as pay_sum,
       (SELECT SUM(amount) FROM loan l 
        WHERE l.date BETWEEN '2001-01-01' AND '2016-03-31' AND l.account_id = a.account_id) as loan_sum
FROM account a
WHERE a.acc_openingdate BETWEEN '2001-01-01' AND '2016-03-31'
  AND a.STATUS = 'open'