2016-09-08 14 views
0

同じ表の別の列test_methodに基づいて列の値authorをコピーしたいとします。 author列の別の列に同じ値の列値をコピーする方法はありますか?

 
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以下

参照テーブルはtest_methodカラムの同じ値からコピーする必要があります。 (何の上書きだけで、チェックする必要があります)

期待される結果がどのようにSQLコマンドを使用して、それを達成することができます

 
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) 

ではありませんか?

答えて

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; 

EDIT:

これは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'; 
+0

テーブルを更新する必要があります。期待されるテーブルは変更後のテーブルです。 –

関連する問題