简体   繁体   English

我无法在 mysql 中没有重复的情况下加入两个表

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

I have two tables:我有两个表:

  1. Members (member_id, member_gender)成员 (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订单 (order_id, member_id, order_amount) 我必须检索有关成员数量、买家数量(至少有 1 个订单的成员)、订单数量的数据但不幸的是我很难,因为当我尝试加入这两个表时我收到重复,我无法计算特殊成员所以我的初始代码是: 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

You can ask the db to count only unique occurrences of the member id您可以要求数据库仅计算成员 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您还可以运行子查询将订单分组,以便在加入成员表之前每个成员只有一行,这意味着如果成员有 2 个订单,则成员数据不会翻倍,如果有,则不会翻三倍3 等

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.通常,“在连接完成之前将 1:M 关系的多方压缩到一行”是管理数据的有用方法,尤其是在需要进行多个连接的情况下。 Getting everything 1:1 means no duplicates pop up以 1:1 比例获取所有内容意味着不会弹出重复项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM