【问题标题】:Processing values in a column for each group为每个组处理列中的值
【发布时间】:2026-01-25 20:45:01
【问题描述】:

我有一个 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 如果该分店是一家特别大的商店,则为 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 只在次要分店购物,因此我们将其从删除中忽略。

【问题讨论】:

    标签: mysql sql database


    【解决方案1】:

    您可以删除以下行:

    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 查询,请使用exists

    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)
              );
    

    【讨论】:

      最近更新 更多