Home Database Mysql Tutorial MYSQL table operations

MYSQL table operations

May 27, 2020 am 08:48 AM
1

When a library is created, tables need to be created next. To create a table, you need to know not only the syntax, but also the column types, indexes, etc. The following will only talk about the syntax for creating tables, and will not describe the column types.

Build a table

Build a table syntax:

CREATE TABLE [IF NOT EXISTS] 表名 (
    字段名1 列类型 [属性] [索引],
    字段名2 列类型 [属性] [索引],
    字段名3 列类型 [属性] [索引],
    ......
) [表类型] [表字符集]
Copy after login

There is a point to note here, the field name should not be the same as the key of mysql If you really want to do this, you need to add ` symbols before and after the field name. This symbol is above the tab key.

Now let's create a user table with fields: user ID, user name, user password, mobile phone number, gender, and birthday.

create table if not exists users(
  user_id int(10) unsigned auto_increment primary key,
  username varchar(16) not null default '' collate utf8mb4_bin comment '用户名',
  userpass char(32) not null collate utf8mb4_bin default '',
  mobile char(11) not null default '' unique,
  gender enum('未知', '男', '女') default '未知',
  birth date not null default '1900-01-01',
  index username(username)
) engine=innodb default charset utf8mb4 collate utf8mb4_general_ci;
Copy after login

Usually, we will create a unique identification field for each table, here is user_id, to facilitate future operations. Collate is set for both username and userpass fields here. This is because these two fields are different from others in that they are case-sensitive. In addition, we created two indexes for the table, namely the mobile field and the username field. A unique index is set for mobile, which means that the mobile phone number cannot be repeated. Creating a general index for username is to speed up searches through username.

View the table and table structure

After the table is created, we want to see if it is really created successfully. You can view all tables under the current library through show tables.

mysql> show tables;
+---------------+
| Tables_in_job |
+---------------+
| users      |
+---------------+
1 row in set
Copy after login

The table is indeed generated successfully, but if you want to see what fields and attributes are in the table, you can check it through desc table name.

Clear and delete tables

Note: Deleting a table is a dangerous operation, so operate with caution!

Delete table syntax: DROP TABLE [IF EXISTS] Table name

No demonstration here.

Clear table syntax: TRUNCATE table name

Here we will focus on the difference between truncate users and delete from users.

  • truncate is equivalent to deleting the table first and then re-creating the table. All data in the table has been reset.

  • While delete only deletes the data of the table, some attribute information of the table, such as the auto-incremented id, will not be reset.

Modify the table

Finally, let’s take a look at how to modify the table. It is placed last because its syntax is the most complicated and it is the most difficult part of table operations. Its syntax is as follows:

ALTER TABLE 数据表名 alter_spec[,alter_spec] ... table options
Copy after login

I have organized common operations. The common syntax and functions are as follows:

  • Add new fields: ALTER TABLE table name ADD field name [FISRT|ALTER column name]

  • Modify fields: ALTER TABLE table name change|modify list Note: Modify and change The difference is that modify can only modify the column type, while change can change the column name in addition to modifying the column type.

  • Delete field: ... DROP column name

  • Add index name: ... ADD INDEX [INDEX_NAME] (index_col1,index_col2, ...)

  • Delete index: ...DROP INDEX INDEX_NAME

  • Delete primary key: ...DROP PRIMARY KEY

  • Add primary key: ... ADD PRIMARY KEY (INDEX_COL1,INDEX_COL2,...)

  • Add unique index: ... ADD UNIQUE [index_name] (index_col1,index_col2,...)

  • Modify the table name: RENAME newName

Let’s practice it

First, add a new field email and place it after userpass.

ALTER TABLE users ADD email VARCHAR(255) NOT NULL DEFAULT '' AFTER userpass;
Copy after login

Modify userpass and change the length to 64 bits

ALTER TABLE users MODIFY userpass CHAR(64) NOT NULL DEFAULT '' COMMENT '用户登录密码';
Copy after login

Modify userpass and change it to auth

ALTER TABLE users CHANGE userpass `auth` char(32) NOT NULL DEFAULT '';
Copy after login

Add a normal index to email

ALTER TABLE users ADD INDEX eamil(email);
Copy after login

Delete email index

ALTER TABLE users DROP INDEX eamil;
Copy after login

Deleting a unique index is the same as deleting a normal index

ALTER TABLE users DROP INDEX mobile;
Copy after login

Add a unique index

ALTER TABLE users ADD UNIQUE mobile(mobile);
或
ALTER TABLE users ADD UNIQUE (mobile);
Copy after login

To delete the primary key, you need to delete aoto_increment before deleting;

ALTER TABLE users MODIFY user_id INT(10) NOT NULL;
ALTER TABLE users DROP PRIMARY KEY;
Copy after login

Add primary key

ALTER TABLE users ADD PRIMARY KEY (user_id);
Copy after login

The above just describes some syntax of table operations, about column types and indexes, etc. If you are interested, you can read the relevant information.

The above is the detailed content of MYSQL table operations. 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

Video Face Swap

Video Face Swap

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

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)

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Apr 02, 2025 pm 07:05 PM

MySQL supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.

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.

See all articles