如何在另一列中复制相同值的列值?

时间:2016-09-08 12:15:54

标签: mysql sql

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

见下表

mysql> select * from testcase;
+------+---------------------+------------------------+------------+
| id   | test_class          | test_method            | author     |
+------+---------------------+------------------------+------------+
| 3062 | IPv4                | InvalidAddress         | N/A        | 
| 3063 | a.b.c.d.AddressIPv4 | InvalidAddress         | larrycai   |
| 3064 | IPv4                | NormalAddress          | N/A        |
| 3065 | a.b.c.d.AddressIPv4 | NormalAddress          | caiyu      |
....
+------+---------------------+------------------------+------------+
202 rows in set (0.00 sec)

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

预期结果是

mysql> select * from testcase;
+------+---------------------+------------------------+------------+
| id   | test_class          | test_method            | author     |
+------+---------------------+------------------------+------------+
| 3062 | IPv4                | InvalidAddress         | larrycai   | 
| 3063 | a.b.c.d.AddressIPv4 | InvalidAddress         | larrycai   |
| 3064 | IPv4                | NormalAddress          | caiyu      |
| 3065 | a.b.c.d.AddressIPv4 | NormalAddress          | caiyu      |
....
+------+---------------------+------------------------+------------+
202 rows in set (0.00 sec)

如何使用SQL命令实现它?

1 个答案:

答案 0 :(得分: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';
相关问题