2016-09-08 3 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; 

편집 : 이것은 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

테이블을 업데이트해야합니다. 예상 된 테이블은 변경 후의 테이블입니다. –

관련 문제