Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL按不同表中的多个列分组_Mysql - Fatal编程技术网

MySQL按不同表中的多个列分组

MySQL按不同表中的多个列分组,mysql,Mysql,我有以下表格布局: Table Data +----------+-------------------------+ | Field | Type | +----------+-------------------------+ | type | enum('type_b','type_a') | | type_id | int(11) unsigned | | data | bigint(20) unsigned

我有以下表格布局:

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\u id,b.customer\u 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;
这并没有给我正确的结果

我尝试了几种方法,左连接、在客户表上连接和按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 a.customer_id, b.customer_id;
假设d中只有一条记录,它是类型a。ta和tb各有两个记录。d中的记录与
d.type\u id=ta.id
上ta中的一条记录匹配。因此,(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;

表别名在哪里?“ta作为a”,“tb作为b”啊,你是对的:)这不是实际的查询,而是一个简化的查询。修好了。哇,太快了!事实上,这正是问题和解决方案。唐克斯·理查德!我来自世界另一端的谦卑的格雷廷:)非常感谢,我也在同一条船上,这是迄今为止我发现的这个问题最直接的解决方案