麻烦在MySQL中总结两部分联盟

时间:2014-11-26 05:03:49

标签: mysql sql select join union

所以我有一个问题不应该太难回答,但无论出于何种原因,我都无法得到它。我需要总结两个不同表的成本。我尝试过一次长连接,但数字本身出错了。我能得到正确数字的唯一方法是进行两次查询并将它们加在一起。但是,我希望它们显示在一个ID下。

SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(p.cost)
FROM store s
JOIN video v ON s.storeId=v.storeId
JOIN previousrental p ON v.videoid=p.videoid
GROUP BY s.storeId

UNION

SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(r.cost)
FROM store s
JOIN video v ON s.storeId=v.storeId
JOIN rental r ON v.videoid=r.videoid
GROUP BY s.storeId

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(p.cost)
FROM store s
INNER JOIN video v ON s.storeId=v.storeId
INNER JOIN (SELECT p.videoid, SUM(p.cost) cost
                FROM previousrental p 
                GROUP BY p.videoid
                UNION 
                SELECT r.videoid, SUM(r.cost) cost
                FROM rental r
                GROUP BY r.videoid
              ) AS p ON v.videoid=p.videoid
GROUP BY s.storeId;

SELECT s.storeId, s.street, s.city, s.state, s.zipcode, 
         SUM(ISNULL(p.cost, 0) + ISNULL(r.cosr, 0))
FROM store s
INNER JOIN video v ON s.storeId = v.storeId
LEFT OUTER JOIN (SELECT videoid, SUM(cost) cost FROM previousrental GROUP BY videoid) p ON v.videoid = p.videoid
LEFT OUTER JOIN (SELECT videoid, SUM(cost) cost FROM rental GROUP BY videoid) r ON v.videoid = r.videoid
GROUP BY s.storeId;

答案 1 :(得分:0)

一种选择是将结果放在子查询中:

SELECT 
    storeId, street, city, state, zipcode, SUM(cost) 
FROM 
    (SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(p.cost) cost
    FROM store s
    JOIN video v ON s.storeId = v.storeId
    JOIN previousrental p ON v.videoid = p.videoid
    GROUP BY s.storeId
    UNION
    SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(r.cost)
    FROM store s
    JOIN video v ON s.storeId = v.storeId
    JOIN rental r ON v.videoid = r.videoid
    GROUP BY s.storeId
) T
GROUP BY storeId

答案 2 :(得分:0)

您可以将联合包装到派生表中,并对其进行推理:

SELECT x.storeId, x.street, x.city, x.state, x.zipcode, SUM(x.cost)
FROM
(
    SELECT s.storeId, s.street, s.city, s.state, s.zipcode, p.cost
    FROM store s
    JOIN video v ON s.storeId=v.storeId
    JOIN previousrental p ON v.videoid=p.videoid

    UNION

    SELECT s.storeId, s.street, s.city, s.state, s.zipcode, r.cost
    FROM store s
    JOIN video v ON s.storeId=v.storeId
    JOIN rental r ON v.videoid=r.videoid
) x
GROUP BY x.storeId, x.street, x.city, x.state, x.zipcode;

请记住按选择中的所有非聚合列进行分组,即使它们是相关的!