Search code examples
mysqljoincountleft-joindistinct

I'm unable to join two tables without a duplicates in mysql


I have two tables:

  1. Members (member_id, member_gender)
  2. Orders (order_id, member_id, order_amount) I have to retrieve data about the amount of members, amount of buyers (members with at least 1 order), amount of orders But unfortunately I have a hard time because when i try to join these two tables i recieve dublicates and I am unable to count distinctive members So my initial code was:SELECT count(m.member_id) AS Amount_of_members ,count(o.order_id) ,sum(o.order_amount) FROM tbl_member m LEFT JOIN tbl_order o ON m.member_id = o.member_id

Solution

  • You can ask the db to count only unique occurrences of the member id

    SELECT count(DISTINCT m.member_id) AS Amount_of_members
    

    You can also run a subquery to group the orders up so there is only one row per member before you join to the members table, which means the members data won't be doubled up if a member has 2 orders, tripled up if they have 3 etc

    SELECT 
      count(m.member_id) AS Amount_of_members ,
      sum(x.count_orders) as total_count_of_orders,
      sum(x.sum_orders) as total_sum_of_orders
    FROM 
      tbl_member m 
      LEFT JOIN (
        SELECT 
          o.member_id,
          count(o.order_id) as count_orders ,
          sum(o.order_amount) as sum_orders
        FROM
          tbl_order o
        GROUP BY o.member_id
     )x ON m.member_id = x.member_id
    

    Generally the "squash the many side of a 1:M relationship down to one row before the join is done" is a helpful way to manage the data, especially if there are multiple joins that need to be made. Getting everything 1:1 means no duplicates pop up