mysql update 에서 subquery 사용 하기

5040 단어 mysqlupdatesubquery
우선,my sql workbench 에서 update 를 실행 할 때 부족 한 것 은 안전 업데이트 모드 를 사용 합 니 다.update sql 내 where 에 id 등 메 인 키 조건 이 지정 되 지 않 으 면 경고 하고 실행 합 니 다.보안 모드 를 닫 고 다음 문 구 를 실행 하면 됩 니 다.
SET SQL_SAFE_UPDATES=0; 

이것 은 my sql 의 update 문장의 스타일 입 니 다:
# Single-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

# Multiple-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

다시 한 번 update 의 제한:1.update 시 업 데 이 트 된 시 계 는 set 와 where 에서 하위 조회 2.update 에 사용 할 수 없습니다.update 시 여러 시 계 를 업데이트 할 수 있 습 니 다.예 를 들 어update table_a a,table_b b set a.b_id=b.id, b.a_id=a.id;3.update 뒤에 임의의 조 회 를 할 수 있 습 니 다.이 역할 은 from 과 같 습 니 다.
다음 과 같은 네티즌 의 예 를 보 여 준다.
mysql> create table IF NOT EXISTS tb (Name varchar(10),Time1 datetime,Time2 date
time,Time3 varchar(8),Time4 varchar(8) );
Query OK, 0 rows affected (0.03 sec)

일부 데 이 터 를 삽입 한 후 하위 조회 가 있 는 update 작업 을 진행 합 니 다.
//   mysql update       
mysql> update tb a,
    -> (select SEC_TO_TIME(sum(TIME_TO_SEC(time3))) col,max(time1) time,name
    -> from tb group by DATE_FORMAT(time1, '%Y-%m-%d'))b
    -> set time4=b.col
    -> where a.name=b.name and a.time1=b.time;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 5  Changed: 4  Warnings: 0

또 예 를 들 면:
//
update tch, (
        SELECT (ta.base_pay-80.0) as pay,ta.tch_id
        FROM t_a ta
        WHERE ta.STATUS = "INTERVIEW"
        AND ta.result = "PASS"
        AND ta.base_pay < 19
        AND ta.tch_id in(
            SELECT DISTINCT
                    tb.tch_id
                FROM
                    t_a tb JOIN tch t2 ON tb.tch_id = t2.id
                WHERE tb.STATUS = "INTERVIEW"
                AND tb.result = "PASS"
                AND tb.base_pay < 190
                AND t2.extra_class_salary IS NULL
        ) 
    ) tmps
set tch.extra_class_salary = tmps.pay
where tch.id = tmps.tch_id;

좋은 웹페이지 즐겨찾기