zoukankan      html  css  js  c++  java
  • MySQL Crash Course #11# Chapter 20. Updating and Deleting Data

    INDEX

    Updating Data

    UPDATE customers
    SET cust_name = 'The Fudds',
        cust_email = 'elmer@fudd.com'
    WHERE cust_id = 10005;

    To delete a column's value, you can set it to NULL (assuming the table is defined to allow NULL values). You can do this as follows:

    UPDATE customers
    SET cust_email = NULL
    WHERE cust_id = 10005;

    Here the NULL keyword is used to save no value to the cust_email column.

    The IGNORE Keyword

    If your UPDATE statement updates multiple rows and an error occurs while updating one or more of those rows, the entire UPDATE operation is cancelled (and any rows updated before the error occurred are restored to their original values). To continue processing updates, even if an error occurs, use the IGNORE keyword, like this:

    UPDATE IGNORE customers ...

    Deleting Data

    DELETE FROM customers
    WHERE cust_id = 10006;

    DELETE takes no column names or wildcard characters. DELETE deletes entire rows, not columns. To delete specific columns use an UPDATE statement (as seen earlier in this chapter).

    Faster Deletes

    If you really do want to delete all rows from a table, don't use DELETE. Instead, use the trUNCATE TABLE statement that accomplished the same thing but does it much quicker (trUNCATE actually drops and recreates the table, instead of deleting each row individually).

    Guidelines for Updating and Deleting Data 

    Here are some best practices that many SQL programmers follow:

    • Never execute an UPDATE or a DELETE without a WHERE clause unless you really do intend to update and delete every row.

    • Make sure every table has a primary key (refer to Chapter 15, "Joining Tables," if you have forgotten what this is), and use it as the WHERE clause whenever possible. (You may specify individual primary keys, multiple values, or value ranges.)

    • Before you use a WHERE clause with an UPDATE or a DELETE, first test it with a SELECT to make sure it is filtering the right recordsit is far too easy to write incorrect WHERE clauses.

    • Use database enforced referential integrity (refer to Chapter 15 for this one, too) so MySQL will not allow the deletion of rows that have data in other tables related to them.

    The bottom line is that MySQL has no Undo button. Be very careful using UPDATE and DELETE, or you'll find yourself updating and deleting the wrong data.

  • 相关阅读:
    MySql行锁等待时间
    日志工具类-Mapper静态调用
    MySql锁机制理解记录
    Flink之TableAPI和SQL(5):表的时间特性
    Flink之TableAPI和SQL(4):表的Sink实现
    Flink之TableAPI和SQL(3):通过TableAPI和SQL表的一些操作(包括查询,过滤,聚集等)
    Flink之TableAPI和SQL(2):表和外部系统的连接方式
    Flink之TableAPI和SQL(1):基本功能描述
    sb 错误
    洛谷 P6189
  • 原文地址:https://www.cnblogs.com/xkxf/p/8889556.html
Copyright © 2011-2022 走看看