MySQL GROUP BY multiple columns from different tables

后端 未结 1 1875
孤街浪徒
孤街浪徒 2021-01-20 00:13

I\'ve got the following table layouts:

Table Data
+----------+-------------------------+
| Field    | Type                    |
+----------+-----------------         


        
1条回答
  •  逝去的感伤
    2021-01-20 01:10

    Your query

    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;
    

    Let's say there is only one record in d, and it is type_a. There are two records in ta and tb each. The record in d matches one of the records in ta on d.type_id=ta.id. Therefore, that combination of (d x ta) allows ANY tb record to remain in the final result. You get an unintended cartesian product.

    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;
    

    0 讨论(0)
提交回复
热议问题