search
HomeDatabaseMysql TutorialMySQL学习13:操作数据表中的记录(一)

操作MySQL数据库中的数据表的记录包括:记录的插入、记录的修改、记录的删除和记录的查询。简单来说、就 是数据表中的记录的增删改查。 一插入记录 MySQL数据库中的数据表的记录的插入包括三种形式,在前面我们操作数据表的时候就已经使用过记录的插入。 那

       操作MySQL数据库中的数据表的记录包括:记录的插入、记录的修改、记录的删除和记录的查询。简单来说、就

是数据表中的记录的增删改查。

       一插入记录

       MySQL数据库中的数据表的记录的插入包括三种形式,在前面我们操作数据表的时候就已经使用过记录的插入。

那只是我们最常使用的一种方式而已,接下来我们来看看记录的三种插入方式:

       (1)INSERT命令

       MySQL数据库中的数据表中插入记录的第一种语法格式,也是最常用的一种语法格式为:

       INSERT [INTO] table_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...;

       例子:

       我们在向数据表中写入记录的同时,首先先来创建一张数据表,并来查看所有字段:

       CREATE TABLE users3(

           id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

           username VARCHAR(20) NOT NULL,

           password VARCHAR(32) NOT NULL,

           age  TINYINT UNSIGNED NOT NULL DEFAULT 10,

           sex BOOLEAN

       );

       DESC users3;


       1)省略所有字段的情况

       下面记录的插入列出了插入字段的各种情况:

       INSERT users3 VALUES(NULL,'Tom','123',25,1);

       INSERT users3 VALUES(NULL,'John','223',DEFAULT,0);

       INSERT users3 VALUES(DEFAULT,'Rose','323',25,1);

       INSERT users3 VALUES(DEFAULT,'Paul','123',23-5+1,1);

       SELECT * FROM users3;


       INSERT users3 VALUES(DEFAULT,'Tom','123',25);


       上面的出错情况表明插入的记录与列的个数不匹配,因此如果我们做记录插入时省略所有字段名称的情况下,要

依次插入与列数相同个数的值,否则记录的写入不成功,向数据表中写记录的时候切记这一点。

        2)插入指定字段的情况:

        INSERT users3(username,password,age) VALUES('Kobe','111',23);

        SELECT * FROM users3;


        3)插入多条记录的情况:

        INSERT users3 VALUES(NULL,'Dave','456',23,0),(NULL,'Jack','456',24,1);

        SELECT * FROM users3;


       (2)INSERT SET命令

       MySQL数据库中向数据表中插入记录的第二种语法格式为:

       INSERT [INTO] table_name SET col_name={expr | DEFAULT},...;

       解释说明:与第一种插入记录方式的区别在于,此方法可以使用子查询(SubQuery)。引发子查询有三种情况,其

中有一种情况叫做由比较运算符引起的子查询,这里等号(=)也可以算是一种典型的比较运算符。此方法还有一个与第

一种方法的区别是,第一种可以一次性插入多条记录,但是第二种方法一次性只能插入一条记录。

       例子:

       INSERT users3 SET username='Jord',password='345';

       SELECT * FROM users3;


       (3)INSERT SELECT命令(超纲)

       MySQL数据库中向数据表中插入记录的第三种语法格式为:

       INSERT [INTO] table_name [(col_name,...)] SELECT ...;

       解释说明:此方法可以将查询结果插入到指定数据表。由于我们现在了解的SELECT语句比较少,现在并不好理

解,但我们还是照常写出例子,学完了后面记录的查询我们也可以回过头来再次学习。

       例子:

       1在插入记录前,先来创建一个空的数据表test:

       CREATE TABLE test(

           id TINYINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,

           username VARCHAR(20)

       );

       2我们将数据表users3中的年龄大于25的记录的username插入到数据表test中:

       INSERT test(username) SELECT username FROM users3 WHERE age > 25;

       3查询数据表test的记录:

       SELECT * FROM test;


       二更新记录

       MySQL数据库更新数据表的记录也是再经常不过的事了,简单的说就是更改某些记录的某些字段,或者重新赋值

等等。更新记录的方式包括单表更新和多表更新,这里我们只学单表更新,多表更新在后面叙述。

       来看看单表更新的语法格式:

       UPDTAE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1 | DEFAULT} [,col_name2=

{expr2 | DEFAULT}] ... [WHERE where_condition];

       (1)省略关键字WHERE的情况

       如果省略关键字WHERE,导致的是将更新所有的记录。

       例子:

       1)更新一列:

       SELECT * FROM users3;

       UPDATE users3 SET age = age + 5;

       SELECT * FROM users3;


       2)更新多列:

       SELECT * FROM users3;

       UPDATE users3 SET age = age - id,sex = 0;

       SELECT * FROM users3;


       (2)有关键字WHERE下指定几条记录更新的情况

       UPDATE users3 SET age = age + 10 WHERE id % 2 =0;

       SELECT * FROM users3;


       三删除记录

       既然MySQL数据库中的数据表的记录有插入和更新,肯定的就有删除记录的情况,删除记录的方式也有两种:单

表删除和多表删除,这里也是只说单表删除。

       单表删除的语法格式:

       DELETE FROM table_name [WHERE where_condition];

       例子:

       指定条件删除,如果不指定删除哪几条记录,将会全部删除。

       DELETE FROM users3 WHERE id = 6;

       SELECT * FROM users3;


       假设我们再重新插入一条记录,那么插入记录的id字段的值是多少呢?

       INSERT users3 VALUES(NULL,'Bob','234',34,1);

       SELECT * FROM users3;


       


Statement
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
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment