• 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.

  • 相关阅读:
    二层设备与三层设备的区别--总结
    转载-vim配置收藏
    Docker入门
    Docker入门
    Docker入门
    Docker入门
    Docker入门
    树莓派进阶之路 (037)
    基于Centos搭建个人 Leanote 云笔记本
    基于CentOS搭建私有云服务
  • 原文地址:https://www.cnblogs.com/xkxf/p/8889556.html
Copyright © 2020-2023  润新知