Mysql 处理每个组的列中的值

Mysql 处理每个组的列中的值,mysql,sql,database,Mysql,Sql,Database,我有一个MySQL客户表和他们购买的店铺分支,类似于以下内容: customer_id | branch_id | is_major_branch ----------------------------------------------- 5 24 1 5 83 0 5

我有一个MySQL客户表和他们购买的店铺分支,类似于以下内容:

    customer_id   |   branch_id   |   is_major_branch
    -----------------------------------------------
        5               24                1
        5               83                0
        5               241               0
        8               66                0
        8               72                0
        9               15                1
        16              31                1
        16              61                1
is_major_branch
is 1,如果该分店是一家特别大的商店

如何删除客户在次要分支机构购物的所有行(is_major_branch=0),除非客户仅在次要分支机构购物?示例结果集:

    customer_id   |   branch_id   |   is_major_branch
    -----------------------------------------------
        5               241               1
        8               66                0
        8               72                0
        9               15                1
        16              31                1
        16              61                1

请注意,客户8仅在一个小分支机构购物,因此我们在删除时忽略它们。

您可以通过以下操作删除行:

delete t
    from t join
         (select customer_id, max(is_major_branch) as max_is_major_branch
          from t
          group by customer_id
         ) tt
         on t.customer_id = tt.customer_id
    where t.is_major_branch = 0 and tt.max_is_major_branch = 1;
如果只需要
选择
查询,请使用
存在

select t.*
from t
where not (t.is_major_branch = 0 and
           exists (select 1 from t t2 where t2.customer_id = t.customer_id and t2.is_major_branch = 1)
          );