如何在不使用union mysql的情况下在一个查询中从两个不同的表中求和

时间:2016-02-03 06:23:09

标签: mysql database

SELECT SUM(amount_paid) AS total_session FROM session 
WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID'
UNION 
SELECT SUM(amount_paid) AS total_subscription FROM subscription 
WHERE subscription.date_enrolled = '2016-02-03'  AND subscription.payment_status = 'PAID'

我只想在别名total_sessiontotal_subscription的两个不同列中显示结果。我怎么能用联盟呢?

2 个答案:

答案 0 :(得分:1)

将每个查询作为子查询放在主SELECT

中,而不是UNION
SELECT 
    (SELECT SUM(amount_paid) FROM session 
    WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID') AS total_paid,
    (SELECT SUM(amount_paid) FROM subscription 
    WHERE subscription.date_enrolled = '2016-02-03'  AND subscription.payment_status = 'PAID') AS total_subscription

答案 1 :(得分:0)

在这种情况下,您可以尝试进行虚假加入,例如

SELECT xx.total_session, yy.total_subscription
FROM (
SELECT '1' as ID, SUM(amount_paid) AS total_session FROM session 
WHERE session.date = '2016-02-03' AND session.payment_status = 'PAID') xx
JOIN (SELECT '1' as ID, SUM(amount_paid) AS total_subscription FROM subscription 
WHERE subscription.date_enrolled = '2016-02-03'  AND subscription.payment_status = 'PAID') yy
ON xx.ID = yy.ID;