MySQL GROUP BY来自不同表的多个列

时间:2011-04-06 10:00:23

标签: mysql

我有以下表格布局:

Table Data
+----------+-------------------------+
| Field    | Type                    |
+----------+-------------------------+
| type     | enum('type_b','type_a') |
| type_id  | int(11) unsigned        |
| data     | bigint(20) unsigned     |
+----------+-------------------------+

Table A and B:

+--------------+------------------+
| Field        | Type             |
+--------------+------------------+
| id           | int(11) unsigned |
| customer_id  | int(11) unsigned |
| ...                             |
+--------------+------------------+

在表格数据中,存在来自某种类型(a或b)的一些测量数据。 现在,我希望客户能够获得两种类型数据a和b的总和。

所以,我想:选择总和,加入a或b并按a.customer_id分组,b.customer_id。

导致以下查询:

SELECT sum(d.data) as total
FROM data d, ta, tb
WHERE
(d.type LIKE "type_a" AND d.type_id = ta.id) 
OR 
(d.type LIKE "type_b" AND d.type_id = tb.id) 
GROUP BY ta.customer_id, tb.customer_id;

这不能让我得到正确的结果......

我尝试了几种方法,左连接,加入客户表和group by customer.id等。是否有人知道我做错了什么?

感谢名单!

1 个答案:

答案 0 :(得分:3)

您的查询

SELECT sum(d.data) as total
FROM data d, ta, tb
WHERE
(d.type LIKE "type_a" AND d.type_id = ta.id) 
OR 
(d.type LIKE "type_b" AND d.type_id = tb.id) 
GROUP BY a.customer_id, b.customer_id;

假设d中只有一条记录,它是type_a。 ta和tb各有两条记录。 d中的记录与d.type_id=ta.id中的一条记录相匹配。因此,(d x ta)的组合允许任何tb记录保留在最终结果中。你得到一个意想不到的笛卡儿产品。

SELECT x.customer_id, SUM(data) total
FROM
(
    SELECT ta.customer_id, d.data
    FROM data d JOIN ta
       ON (d.type LIKE "type_a" AND d.type_id = ta.id) 
    UNION ALL
    SELECT tb.customer_id, d.data
    FROM data d JOIN tb
       ON (d.type LIKE "type_b" AND d.type_id = tb.id) 
) X
GROUP BY x.customer_id;