Home Database Mysql Tutorial What are the basic statements for database addition, deletion, modification and query?

What are the basic statements for database addition, deletion, modification and query?

Nov 04, 2020 am 10:03 AM
mysql Add, delete, modify and check database

Basic statements for add, delete, modify and query in the database: "INSERT INTO table name field list VALUES (value list)", "DELETE FROM table name WHERE clause", "UPDATE table name SET column = value WHERE clause" , "SELECT * FROM table name".

What are the basic statements for database addition, deletion, modification and query?

(Recommended tutorial: mysql video tutorial)

Basic statements for database addition, deletion, modification and query

Add data to the database

In MySQL, you can use the INSERT INTO statement to insert one or more rows of tuple data into an existing table in the database .

Grammar format:

INSERT INTO 表名 ( 列名1, 列名2,...列名N )
                 VALUES
                 ( 值1, 值2,...值N );
Copy after login

If the data is character type, single quotes or double quotes must be used, such as: "value".

  • Table name: Specify the name of the table to be operated on.

  • Column name: Specify the column name into which data needs to be inserted. If data is inserted into all columns in the table, all column names can be omitted, and INSERT

    VALUES(…) can be used directly.

  • VALUE clause: This clause contains the list of data to be inserted. The order of data in the data list should correspond to the order of columns.

  • Example: Insert a new record in the tb_courses table, the course_id value is 1, the course_name value is "Network", the course_grade value is 3, and the info value is "Computer Network".

    Before performing the insert operation, check the tb_courses table

    mysql> SELECT * FROM tb_courses;
    Empty set (0.00 sec)
    Copy after login

    The query result shows that the current table content is empty and there is no data. Next, perform the insert data operation. The input SQL statement and execution process are as follows shown.

    mysql> INSERT INTO tb_courses
        -> (course_id,course_name,course_grade,course_info)
        -> VALUES(1,'Network',3,'Computer Network');
    Query OK, 1 rows affected (0.08 sec)
    
    mysql> SELECT * FROM tb_courses;
    +-----------+-------------+--------------+------------------+
    | course_id | course_name | course_grade | course_info      |
    +-----------+-------------+--------------+------------------+
    |         1 | Network     |            3 | Computer Network |
    +-----------+-------------+--------------+------------------+
    1 row in set (0.00 sec)
    Copy after login

    You can see that the record was inserted successfully. When inserting data, all fields of the tb_courses table are specified, so new values ​​will be inserted for each field.

    Note:

    • The order of column names after the INSERT statement may not be the order when the tb_courses table is defined, that is, when inserting data, there is no need to insert it in the order defined by the table. Just make sure that the order of the values ​​is the same as the order of the column fields.

    • When using INSERT to insert data, the column name list column_list is allowed to be empty. At this time, the value list needs to specify a value for each field of the table, and the order of the values ​​must be the same as in the data table. The fields are defined in the same order.

    Note: Although you can ignore the column name of the inserted data when using INSERT to insert data, if the value does not contain the column name, the value after the VALUES keyword must not only be complete, but also The order must be the same as the order of the columns when the table was defined. If the structure of the table is modified and columns are added, deleted, or their positions are changed, these operations will cause the order in which data is inserted in this way to change at the same time. If you specify column names, they will not be affected by table structure changes.

    Database deletion

    In MySQL, you can use the DELETE statement to delete one or more rows of data in a table.

    The syntax format is:

    DELETE FROM 表名 [WHERE 子句] [ORDER BY 子句] [LIMIT 子句]
    Copy after login

    Delete specified data:

    DELETE FROM 表名称 WHERE 列名称 = 值
    Copy after login

    The syntax description is as follows:

    • Table name: Specify the table name from which data is to be deleted.

    • ORDER BY clause: Optional. Indicates that when deleting, rows in the table will be deleted in the order specified in the clause.

    • WHERE clause: Optional. Indicates that the deletion conditions are limited for the deletion operation. If this clause is omitted, it means that all rows in the table are deleted.

    • LIMIT clause: Optional. Used to tell the server the maximum number of rows to be deleted before the control command is returned to the client.

    Note: When the WHERE condition is not used, all data will be deleted.

    Example 1: Delete all data in the table

    Delete all data in the tb_courses_new table. The input SQL statement and execution results are as follows.

    mysql> DELETE FROM tb_courses_new;
    Query OK, 3 rows affected (0.12 sec)
    mysql> SELECT * FROM tb_courses_new;
    Empty set (0.00 sec)
    Copy after login

    Example 2: Delete data in the table based on conditions

    In the tb_courses_new table, delete the record with course_id 4. The input SQL statement and execution results are as follows.

    mysql> DELETE FROM tb_courses
        -> WHERE course_id=4;
    Query OK, 1 row affected (0.00 sec)
    mysql> SELECT * FROM tb_courses;
    +-----------+-------------+--------------+------------------+
    | course_id | course_name | course_grade | course_info      |
    +-----------+-------------+--------------+------------------+
    |         1 | Network     |            3 | Computer Network |
    |         2 | Database    |            3 | MySQL            |
    |         3 | Java        |            4 | Java EE          |
    +-----------+-------------+--------------+------------------+
    3 rows in set (0.00 sec)
    Copy after login

    It can be seen from the running results that the record with course_id 4 has been deleted.

    Database modification data

    In MySQL, you can use the UPDATE statement to modify and update data in one or more tables.

    The syntax format is:

    UPDATE 表名 SET 字段=值 [WHERE 子句 ]
    [ORDER BY 子句] [LIMIT 子句]
    Copy after login

    Example:

    UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
    Copy after login

    The syntax description is as follows:

    • Table name: used to specify the update table name.

    • SET clause: used to specify the column name and its column value to be modified in the table. Among them, each specified column value can be an expression or the default value corresponding to the column. If a default value is specified, the column value can be represented by the keyword DEFAULT.

    • WHERE clause: Optional. Used to limit the rows in the table to be modified. If not specified, all rows in the table will be modified.

    • ORDER BY clause: Optional. Used to limit the order in which rows in a table are modified.

    • LIMIT clause: Optional. Used to limit the number of rows that are modified.

    注意:修改一行数据的多个列值时,SET 子句的每个值用逗号分开即可。

    示例1:修改表中的数据

    在 tb_courses_new 表中,更新所有行的 course_grade 字段值为 4,输入的 SQL 语句和执行结果如下所示。

    mysql> UPDATE tb_courses_new
        -> SET course_grade=4;
    Query OK, 3 rows affected (0.11 sec)
    Rows matched: 4  Changed: 3  Warnings: 0
    
    mysql> SELECT * FROM tb_courses_new;
    +-----------+-------------+--------------+------------------+
    | course_id | course_name | course_grade | course_info      |
    +-----------+-------------+--------------+------------------+
    |         1 | Network     |            4 | Computer Network |
    |         2 | Database    |            4 | MySQL            |
    |         3 | Java        |            4 | Java EE          |
    |         4 | System      |            4 | Operating System |
    +-----------+-------------+--------------+------------------+
    4 rows in set (0.00 sec)
    Copy after login

    示例1:根据条件修改表中的数据

    在 tb_courses 表中,更新 course_id 值为 2 的记录,将 course_grade 字段值改为 3.5,将 course_name 字段值改为“DB”,输入的 SQL 语句和执行结果如下所示。

    mysql> UPDATE tb_courses_new
        -> SET course_name='DB',course_grade=3.5
        -> WHERE course_id=2;
    Query OK, 1 row affected (0.13 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
    mysql> SELECT * FROM tb_courses_new;
    +-----------+-------------+--------------+------------------+
    | course_id | course_name | course_grade | course_info      |
    +-----------+-------------+--------------+------------------+
    |         1 | Network     |            4 | Computer Network |
    |         2 | DB          |          3.5 | MySQL            |
    |         3 | Java        |            4 | Java EE          |
    |         4 | System      |            4 | Operating System |
    +-----------+-------------+--------------+------------------+
    4 rows in set (0.00 sec)
    Copy after login

    注意:保证 UPDATE 以 WHERE 子句结束,通过 WHERE 子句指定被更新的记录所需要满足的条件,如果忽略 WHERE 子句,MySQL 将更新表中所有的行。

    数据库查询数据

    在 MySQL 中,可以使用 SELECT 语句来查询数据。查询数据是指从数据库中根据需求,使用不同的查询方式来获取不同的数据,是使用频率最高、最重要的操作。

    SELECT 的语法格式如下:

    SELECT
    {* | <字段列名>}
    [
    FROM <表 1>, <表 2>…
    [WHERE <表达式>
    [GROUP BY <group by definition>
    [HAVING <expression> [{<operator> <expression>}…]]
    [ORDER BY <order by definition>]
    [LIMIT[<offset>,] <row count>]
    ]
    Copy after login

    其中,各条子句的含义如下:

    • {*|<字段列名>}包含星号通配符的字段列表,表示所要查询字段的名称。

    • <表 1>,<表 2>…,表 1 和表 2 表示查询数据的来源,可以是单个或多个。

    • WHERE <表达式>是可选项,如果选择该项,将限定查询数据必须满足该查询条件。

    • GROUP BY< 字段 >,该子句告诉 MySQL 如何显示查询出来的数据,并按照指定的字段分组。

    • [ORDER BY< 字段 >],该子句告诉 MySQL 按什么样的顺序显示查询出来的数据,可以进行的排序有升序(ASC)和降序(DESC),默认情况下是升序。

    • [LIMIT[,]],该子句告诉 MySQL 每次显示查询出来的数据条数。

    下面先介绍一些简单的 SELECT 语句,关于 WHERE、GROUP BY、ORDER BY 和 LIMIT 等限制条件就不细说了。

    1、查询表中所有字段

    查询所有字段是指查询表中所有字段的数据。MySQL 提供了以下 2 种方式查询表中的所有字段。

    SELECT 可以使用“*”查找表中所有字段的数据,语法格式如下:

    SELECT * FROM 表名;
    Copy after login

    使用“*”查询时,只能按照数据表中字段的顺序进行排列,不能改变字段的排列顺序。

    示例:从 tb_students_info 表中查询所有字段的数据,SQL 语句和运行结果如下所示。

    mysql> use test_db;
    Database changed
    mysql> SELECT * FROM tb_students_info;
    +----+--------+---------+------+------+--------+------------+
    | id | name   | dept_id | age  | sex  | height | login_date |
    +----+--------+---------+------+------+--------+------------+
    |  1 | Dany   |       1 |   25 | F    |    160 | 2015-09-10 |
    |  2 | Green  |       3 |   23 | F    |    158 | 2016-10-22 |
    |  3 | Henry  |       2 |   23 | M    |    185 | 2015-05-31 |
    |  4 | Jane   |       1 |   22 | F    |    162 | 2016-12-20 |
    |  5 | Jim    |       1 |   24 | M    |    175 | 2016-01-15 |
    |  6 | John   |       2 |   21 | M    |    172 | 2015-11-11 |
    |  7 | Lily   |       6 |   22 | F    |    165 | 2016-02-26 |
    |  8 | Susan  |       4 |   23 | F    |    170 | 2015-10-01 |
    |  9 | Thomas |       3 |   22 | M    |    178 | 2016-06-07 |
    | 10 | Tom    |       4 |   23 | M    |    165 | 2016-08-05 |
    +----+--------+---------+------+------+--------+------------+
    10 rows in set (0.26 sec)
    Copy after login

    结果显示,使用“*”通配符时,将返回所有列,数据列按照创建表时的顺序显示。

    注意:一般情况下,除非需要使用表中所有的字段数据,否则最好不要使用通配符“*”。虽然使用通配符可以节省输入查询语句的时间,但是获取不需要的列数据通常会降低查询和所使用的应用程序的效率。使用“*”的优势是,当不知道所需列的名称时,可以通过“*”获取它们。

    2、查询表中指定的字段

    查询表中的某一个字段的语法格式为:

    SELECT < 列名 > FROM < 表名 >;
    Copy after login

    示例:

    查询 tb_students_info 表中 name 列所有学生的姓名,SQL 语句和运行结果如下所示。

    mysql> SELECT name FROM tb_students_info;
    +--------+
    | name   |
    +--------+
    | Dany   |
    | Green  |
    | Henry  |
    | Jane   |
    | Jim    |
    | John   |
    | Lily   |
    | Susan  |
    | Thomas |
    | Tom    |
    +--------+
    10 rows in set (0.00 sec)
    Copy after login

    输出结果显示了 tb_students_info 表中 name 字段下的所有数据。

    使用 SELECT 声明可以获取多个字段下的数据,只需要在关键字 SELECT 后面指定要查找的字段名称,不同字段名称之间用逗号“,”分隔开,最后一个字段后面不需要加逗号,语法格式如下:

    SELECT <字段名1>,<字段名2>,…,<字段名n> FROM <表名>;
    Copy after login

    示例:

    从 tb_students_info 表中获取 id、name 和 height 三列,SQL 语句和运行结果如下所示。

    mysql> SELECT id,name,height
        -> FROM tb_students_info;
    +----+--------+--------+
    | id | name   | height |
    +----+--------+--------+
    |  1 | Dany   |    160 |
    |  2 | Green  |    158 |
    |  3 | Henry  |    185 |
    |  4 | Jane   |    162 |
    |  5 | Jim    |    175 |
    |  6 | John   |    172 |
    |  7 | Lily   |    165 |
    |  8 | Susan  |    170 |
    |  9 | Thomas |    178 |
    | 10 | Tom    |    165 |
    +----+--------+--------+
    10 rows in set (0.00 sec)
    Copy after login

    输出结果显示了 tb_students_info 表中 id、name 和 height 三个字段下的所有数据。

    更多编程相关知识,请访问:编程视频!!

    The above is the detailed content of What are the basic statements for database addition, deletion, modification and query?. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

    MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

    Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

    Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

    How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

    Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

    MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

    MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

    How to view database password in Navicat for MariaDB? How to view database password in Navicat for MariaDB? Apr 08, 2025 pm 09:18 PM

    Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

    MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

    MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

    How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

    Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

    How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

    You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

    See all articles