【问题标题】:how to copy the column values for the same value in another column?如何复制另一列中相同值的列值?
【发布时间】:2017-01-16 08:51:48
【问题描述】:

我想根据同一张表中的另一列 test_method 复制列值 author。

见下表

mysql> 从测试用例中选择 *; +--------+---------------------+-------- ----+------------+ |编号 |测试类 |测试方法 |作者 | +--------+---------------------+-------- ----+------------+ | 3062 | IPv4 |无效地址 |不适用 | | 3063 | a.b.c.d.地址IPv4 |无效地址 |拉里菜 | | 3064 | IPv4 |普通地址 |不适用 | | 3065 | a.b.c.d.地址IPv4 |普通地址 |彩玉 | …… +--------+---------------------+-------- ----+------------+ 202 行(0.00 秒)

author 列中的值N/A 需要从test_method 列的相同值复制。 (无需检查,直接覆盖)

预期结果是

mysql> 从测试用例中选择 *; +--------+---------------------+-------- ----+------------+ |编号 |测试类 |测试方法 |作者 | +--------+---------------------+-------- ----+------------+ | 3062 | IPv4 |无效地址 |拉里菜 | | 3063 | a.b.c.d.地址IPv4 |无效地址 |拉里菜 | | 3064 | IPv4 |普通地址 |彩玉 | | 3065 | a.b.c.d.地址IPv4 |普通地址 |彩玉 | …… +--------+---------------------+-------- ----+------------+ 202 行(0.00 秒)

如何使用 SQL 命令实现?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    这是你想要的吗?

    select t.id, t.class, t.test_method,
           (case when t.author = 'N/A'
                 then (select t2.author
                       from t t2
                       where t2.test_method = t.test_method and
                             t2.author <> 'N/A'
                       limit 1
                      )
                 else t.author
             end) as author
    from t;
    

    您也可以使用聚合和join:

    select t.id, t.class, t.test_method,
           (case when t.author = 'N/A' then tt.author else t.author end) as author
    from t left join
         (select test_method, max(author) as author
          from t
          where author <> 'N/A'
          group by test_method
         ) tt
         on t.test_method = tt.test_method;
    

    编辑:

    作为update,这很容易做到。例如:

    update t 
        from t left join
             (select test_method, max(author) as author
              from t
              where author <> 'N/A'
              group by test_method
             ) tt
             on t.test_method = tt.test_method;
        set t.author = tt.author
        where t.author = 'N/A';
    

    【讨论】:

    • 我需要更新表格。预期的表是更改后的表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多