SQL 入门 6:SQL 数据操作:更新与删除

艺帆风顺 发布于 2025-04-18 30 次阅读


USE sql_invoicing;

日期:2025 年 4 月 1 日。以下为 SQL 中数据更新与删除的用法解析。

学习内容

  1. 更新数据(UPDATE)

  • UPDATE 修改指定表的列值,SET 定义更新内容,WHERE 指定条件。
  • 可设为具体值、DEFAULT、运算结果或 NULL(若列允许)。
  • 单行更新通常用主键(如 invoice_id),多行更新用其他条件。
  • 更新多行

    • WHERE 支持多条件,如 IN 指定多值。
    • 影响范围取决于条件匹配的行数。
  • 子查询在 UPDATE 中使用

    • WHERE 中嵌入子查询,子查询结果作为条件。
    • 单值结果用 =,多值结果用 IN
  • 删除行(DELETE)

    • DELETE FROM 删除指定表行,WHERE 定义条件。
    • 可结合子查询定位目标行。

    示例代码与讲解

    1. 更新单行

    UPDATE invoices
    SET payment_total = 10, payment_date = '2019-03-07'
    WHERE invoice_id = 1;
    • 更新 invoices 中 invoice_id = 1 的行,设置付款金额为 10,付款日期为 2019-03-07。
    UPDATE invoices
    SET payment_total = DEFAULT, payment_date = NULL
    WHERE invoice_id = 1;
    • 将同一行恢复默认值和 NULL,需列支持。
    UPDATE invoices
    SET payment_total = invoice_total * 0.5, payment_date = due_date
    WHERE invoice_id = 1;
    • 设置付款金额为发票总额的 50%,付款日期为截止日期(due_date)。

    2. 更新多行

    UPDATE invoices
    SET payment_total = invoice_total * 0.5, payment_date = due_date
    WHERE client_id = 3;
    • 更新 client_id = 3 的所有行(非主键,可能多行)。
    UPDATE invoices
    SET payment_total = invoice_total * 0.5, payment_date = due_date
    WHERE client_id IN (34);
    • 更新 client_id 为 3 或 4 的所有行。

    3. 子查询更新

    UPDATE invoices
    SET payment_total = invoice_total * 0.5, payment_date = due_date
    WHERE client_id IN (
        SELECT client_id
        FROM clients
        WHERE name = 'Myworks'
    );
    • 更新 clients 表中 name = 'Myworks' 对应客户的所有发票。
    • 子查询返回多值,用 IN

    4. 删除行

    DELETE FROM invoices
    WHERE client_id = (
        SELECT client_id
        FROM clients
        WHERE name = 'Myworks'
    );
    • 删除 clients 表中 name = 'Myworks' 对应客户的所有发票。
    • 子查询返回单值,用 =

    作业

    1. 更新积分

    USE sql_store;
    UPDATE customers
    SET points = points + 50
    WHERE birth_date >= '1990-01-01';
    • 为 1990 年后出生的客户增加 50 积分。

    2. 子查询更新

    UPDATE orders
    SET comments = 'Gold customer'
    WHERE customer_id IN (
        SELECT customer_id
        FROM customers
        WHERE points >= 3000
    );
    • 为积分 ≥ 3000 的客户订单添加“Gold customer”备注。

    总结

    本次解析了数据更新(单行、多行、子查询)和行删除。基于 sql_invoicing 和 sql_store 数据库。后续将探讨聚合函数与分组查询。