search
HomeDatabaseMysql TutorialMySQL操作数据库和表的常用命令新手教程_MySQL

我是新手

学习如何管理和导航MySQL数据库和表是要掌握的首要任务之一,下面的内容将主要对MySQL的数据库和表的一些常用命令进行总结,一些我们不得不掌握的命令,一些信手拈来的命令。

处理数据库

1.查看数据库

获取服务器上的数据库列表通常很有用。执行show databases;命令就可以搞定。

代码如下:


mysql> show databases;

2.创建数据库

代码如下:


mysql> create database db_test;
Query OK, 1 row affected (0.00 sec)

3.使用数据库

数据库一旦创建,就可以通过“使用”(use命令)数据库,将其指定为默认的工作数据库。

代码如下:


mysql> use db_test;
Database changed

4.删除数据库

删除数据库的方式与创建的方式很相似。可以在mysql客户端中使用drop命令删除数据库,如下:

代码如下:


mysql> drop database db_test;
Query OK, 0 rows affected (0.00 sec)

处理表

这里将对如何创建、列出、查看、删除和修改MySQL数据库表。

1.创建表

表通过create table语句来创建。创建表的过程中会使用非常多的选项和子句,在这里完全总结一遍也是不现实的,这里只是总结最普遍的,以后遇到别的,再单个总结。创建表的一般用法如下:

代码如下:


mysql> create table tb_test(
    -> id int unsigned not null auto_increment,
    -> firstname varchar(25) not null,
    -> lastname varchar(25) not null,
    -> email varchar(45) not null,
    -> phone varchar(10) not null,
    -> primary key(id));
Query OK, 0 rows affected (0.03 sec)

记住,表至少包含一列。另外,创建表之后总是可以再回过头来修改表的结构。无论当前是否在使用目标数据库,都可以创建表,只要在表名前面加上目标数据库即可。例如:

代码如下:


mysql> create table db_test.tb_test(
    -> id int unsigned not null auto_increment,
    -> firstname varchar(25) not null,
    -> lastname varchar(25) not null,
    -> email varchar(45) not null,
    -> phone varchar(10) not null,
    -> primary key(id));
Query OK, 0 rows affected (0.03 sec)

2.有条件的创建表

在默认情况下,如果试图创建一个已经存在的表,MySQL会产生一个错误。为了避免这个错误,create table语句提供了一个子句,如果你希望在目标表已经存在的情况下简单地退出表创建,就可以使用这个子句。例如:

代码如下:


mysql> create table if not exists db_test.tb_test(
    -> id int unsigned not null auto_increment,
    -> firstname varchar(25) not null,
    -> lastname varchar(25) not null,
    -> email varchar(45) not null,
    -> phone varchar(10) not null,
    -> primary key(id));
Query OK, 0 rows affected, 1 warning (0.00 sec)

无论是否已经创建,都会在返回到命令提示窗口时显示“Query OK”消息。

3.复制表

基于现有的表创建新表是一项很容易的任务。以下代码将得到tb_test表的一个副本,名为tb_test2:

代码如下:


mysql> create table tb_test2 select * from db_test.tb_test;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

将向数据库增加一个相同的表tb_test2。而有的时候,可能希望只基于现有表的几个列创建一个表。通过create select语句中指定列就可以实现:

代码如下:


mysql> describe tb_test;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(25)      | NO   |     | NULL    |                |
| lastname  | varchar(25)      | NO   |     | NULL    |                |
| email     | varchar(45)      | NO   |     | NULL    |                |
| phone     | varchar(10)      | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
mysql> create table tb_test2 select id, firstname, lastname, email from tb_test;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> describe tb_test2;
+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id        | int(10) unsigned | NO   |     | 0       |       |
| firstname | varchar(25)      | NO   |     | NULL    |       |
| lastname  | varchar(25)      | NO   |     | NULL    |       |
| email     | varchar(45)      | NO   |     | NULL    |       |
+-----------+------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

4.创建临时表

有的时候,当工作在非常大的表上时,可能偶尔需要运行很多查询获得一个大量数据的小的子集,不是对整个表运行这些查询,而是让MySQL每次找出所需的少数记录,将记录保存到一个临时表可能更快一些,然后对这些临时表进行查询操作。可以通过使用temporary关键字和create table语句来实现。

代码如下:


mysql> create temporary table emp_temp select firstname, lastname from tb_test;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0


临时表的创建与其它表一样,只是它们存储在操作系统指定的临时目录中。临时表将在你连接MySQL期间存在,当你断开时,MySQL将自动删除表并释放所有的内存空间;当然了,你也可以手动的使用drop table命令删除临时表。

5.查看数据库中可用的表

可以使用show tables命令完成。例如:

代码如下:


mysql> show tables;
+-------------------+
| Tables_in_db_test |
+-------------------+
| tb_test           |
| tb_test2          |
+-------------------+
2 rows in set (0.00 sec)

6.查看表结构

可以使用describe语句查看表结构,例如:

代码如下:


mysql> describe tb_test;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(25)      | NO   |     | NULL    |                |
| lastname  | varchar(25)      | NO   |     | NULL    |                |
| email     | varchar(45)      | NO   |     | NULL    |                |
| phone     | varchar(10)      | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

另外,使用show命令也能得到相同的结果,例如:

代码如下:


mysql> show columns in tb_test;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(25)      | NO   |     | NULL    |                |
| lastname  | varchar(25)      | NO   |     | NULL    |                |
| email     | varchar(45)      | NO   |     | NULL    |                |
| phone     | varchar(10)      | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

7.删除表

删除表是使用drop table语句实现的,其语法如下:

代码如下:


drop [temporary] table [if exists] tbl_name [, tbl_name, ...]

8.更改表结构

我们会发现,我们会经常修改和改进表结构,特别是在开发初期;但是,每次进行修改时不必都先删除再重新创建表。相反,可以使用alter语句修改表的结构。利用这个语句,可以再必要时删除、修改和增加列。和create table一样,alter table提供了很多子句、关键字和选项。这里只是会说一些简单的使用,比如在表tb_demo表中插入一列,表示email,代码如下:

代码如下:


mysql> alter table tb_demo add column email varchar(45);
Query OK, 0 rows affected (0.14 sec)
Records: 0  Duplicates: 0  Warnings: 0

新的列放在表的最后位置。不过,还可以使用适当的关键字(包括first、after和last)来控制新列的位置。如果想修改表,比如,刚刚加的email,我想加入一个not null控制,代码可以是这样的:

代码如下:


mysql> alter table tb_demo change email email varchar(45) not null;
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0


如果觉的这个email这列没有存在的必要了,可以使用下面的代码删除它,例如:

代码如下:


mysql> alter table tb_demo drop email;
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

我不是新手

这篇文章大体上总结了与MySQL打交道时常用的一些命令,希望对大家有帮助。看完这篇文章,你应该认为你已经不是新手了,如果上面的命令你都实践过一遍以后,你应该比60%的人都熟悉MySQL数据库。就是这样,越简单的东西,越是有很多人不会。

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
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

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 Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools