Table of Contents
Create data table
Open database
View the data table structure
Insert records
Looking up table data
Basic constraints on table creation
NULL and NOT NULL in fields
AUTO_INCREMENT
Set the primary key
DEFAULT
Home Database Mysql Tutorial Detailed explanation of MySQL data table operations

Detailed explanation of MySQL data table operations

Mar 26, 2017 pm 02:03 PM

Create data table

Open database

USE database name

mysql> USE D1;
Database changed
Copy after login

Use USE D1; means open database D1 , we can view the currently open database through SELECT DATABASE();:

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| d1         |
+------------+1 row in set (0.00 sec)
Copy after login

Create data table

CREATE TABLE [IF NOT EXISTS] table_name (
column_name datatype,
......
)

This structure is very simple, for [IF NOT EXISTS], in the first article "MySQL Basic Operations" has already been explained and will not be repeated here.

Let’s create a data tabletable1:

mysql> CREATE TABLE table1(
    -> username VARCHAR(20),
    -> age TINYINT UNSIGNED,
    -> salary FLOAT(8,2) UNSIGNED
    -> );
Query OK, 0 rows affected (0.74 sec)
Copy after login

Note that UNSIGNED here represents an unsigned value, which is a positive number. You can review the "MySQL basic data types" to view , TINYINT UNSIGNED represents a value between 0 ~ 255.

This prompts that the creation is successful. We can verify it through the following statement:

SHOW TABLES [FROM db_name][LIKE 'pattern' | WHERE expr]

mysql> SHOW TABLES FROM D1;
+--------------+
| Tables_in_d1 |
+--------------+
| table1       |
+--------------+1 row in set (0.00 sec)
Copy after login

Here we can see that table1 is created.

View the data table structure

SHOW COLUMNS FROM tbl_name

mysql> SHOW COLUMNS FROM table1;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| username | varchar(20)         | YES  |     | NULL    |       |
| age      | tinyint(3) unsigned | YES  |     | NULL    |       |
| salary   | float(8,2) unsigned | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+3 rows in set (0.10 sec)
Copy after login

Insert records

After creating the table, you need to write the data Now, insert records through the following statement:

INSERT [INTO] tbl_name [(col_name,...)] VALUE(val,...)

here[(col_name,...)] is optional. If it is not added, the values ​​in VALUE must correspond to the fields of the data table one by one, otherwise it cannot be inserted. Let’s take a look:

mysql> INSERT table1 VALUE("LI",20,6500.50);
Query OK, 1 row affected (0.14 sec)
Copy after login

The VALUE brackets here correspond to the fields of table1 one-to-one, which are username="LI", age=20, salary=6500.50

We will insert another piece of data below, but there is no correspondence:

mysql> INSERT table1 Value("Wang",25);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
Copy after login

cannot be inserted because no salary value is given.

By adding [(col_name,...)], you can flexibly insert data:

mysql> INSERT table1(username,age) VALUE("Wang",25);
Query OK, 1 row affected (0.11 sec)
Copy after login

table1 corresponds to VALUE one-to-one.

Looking up table data

Two pieces of data have been inserted previously. You can look up table data through the following statement:

SELECT expr,... FROM tbl_name

For the database search statement SELECT, there is a lot of content. The following article will explain it in detail. We use a simple statement to find the contents of the table:

mysql> SELECT * FROM table1
    -> ;
+----------+------+---------+
| username | age  | salary  |
+----------+------+---------+
| LI       |   20 | 6500.50 |
| Wang     |   25 |    NULL |
+----------+------+---------+2 rows in set (0.00 sec)
Copy after login

Note that the MySQL statement starts with "; "At the end, if you forget to write, the statement cannot be executed, just add a semicolon after the arrow; here we can see that there are two pieces of data just written in the table.

Basic constraints on table creation

NULL and NOT NULL in fields

When creating a table, we can set whether the field can be empty. If it cannot be empty, , then when inserting data, it cannot be empty.

Let’s create a data tabletable2:

mysql> CREATE TABLE table2(
    -> username VARCHAR(20) NOT NULL,
    -> age TINYINT UNSIGNED NULL,
    -> salary FLOAT(8,2)
    -> );
Copy after login

Here username is non-empty, age is NULL, salary is not written, let’s check the table structure:

mysql> SHOW COLUMNS FROM table2;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| username | varchar(20)         | NO   |     | NULL    |       |
| age      | tinyint(3) unsigned | YES  |     | NULL    |       |
| salary   | float(8,2)          | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+3 rows in set (0.01 sec)
Copy after login

From here we can see that NULL for username is NO, and the other two fields are YES. For fields that can be empty, writing NULL or not means they can be empty.

AUTO_INCREMENT

AUTO_INCREMENT

auto_increment, auto automatic, increment means increase. When combined, it means automatic increase, that is, it can automatically increase according to the to the highest sequential number.

  • can only be used for primary keys (the primary key represents the unique representation of the data in the table, and the data in the table can be distinguished by the primary key)

  • Default In this case, it is 1, and the increment is 1

Let’s do the following:

mysql> CREATE TABLE table3(
    -> id SMALLINT UNSIGNED AUTO_INCREMENT,
    -> username VARCHAR(20)
    -> );
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
Copy after login

An error is reported because the id is not set as the primary key.

Set the primary key

PRIMARY KEY

  • ##Primary key constraints

  • Each The table can only have one primary key

  • The primary key ensures the uniqueness of the record

  • The primary key is automatically NOT NULL

Then we add the primary key and do it again:

mysql> CREATE TABLE table3(
    -> id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    -> username VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.42 sec)
Copy after login

Pay attention to the order, PRIMARY KEY should be placed last.

In this way, we have created it successfully. Let’s insert the data one by one and check the results:

mysql> INSERT table3(username) VALUES("Zhang");
Query OK, 1 row affected (0.09 sec)

mysql> INSERT table3(username) VALUES("Weng");
Query OK, 1 row affected (0.07 sec)

mysql> INSERT table3(username) VALUES("Chen");
Query OK, 1 row affected (0.09 sec)

mysql> SELECT * FROM table3;
+----+----------+
| id | username |
+----+----------+
|  1 | Zhang    |
|  2 | Weng     |
|  3 | Chen     |
+----+----------+3 rows in set (0.00 sec)
Copy after login

We can see that the IDs are automatically numbered, from small to large.

Unique Constraint

UNIQUE KEY

    ##Unique Constraint
  • ##Unique Constraint Ensure that records are non-repeatable (unique)
  • The unique constraint can be empty (NULL)
  • There can be multiple unique constraints
  • mysql> CREATE TABLE table4(
        -> id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        -> username VARCHAR(20) UNIQUE KEY,
        -> age TINYINT UNSIGNED
        -> );
    Query OK, 0 rows affected (0.43 sec)
    
    mysql> INSERT table4(username) VALUE("Li");
    Query OK, 1 row affected (0.11 sec)
    
    mysql> INSERT table4(username) VALUE("Li");
    ERROR 1062 (23000): Duplicate entry 'Li' for key 'username'
    
    mysql> INSERT table4(username) VALUE("Chen");
    Query OK, 1 row affected (0.10 sec)
    Copy after login

    For username, we set it as a unique constraint, so Li cannot be created repeatedly, just change it to "Chen". Note that this is just an experiment. In actual operation, the same names are common, and the data table should be established according to the actual situation.
Default value DEFAULT

Set the default value through

DEFAULT

. If the corresponding value is not given when inserting data, then the default value will be used. The following example That is to set the default value of number to 3. When inserting data, because number is not given, the default value is 3.

mysql> CREATE TABLE table5(
    -> number ENUM("1","2","3") DEFAULT "3",
    -> username VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.41 sec)

mysql> INSERT table5(username) VALUES("Luo");
Query OK, 1 row affected (0.10 sec)

mysql> INSERT table5(username) VALUES("Fang");
Query OK, 1 row affected (0.15 sec)

mysql> SELECT * FROM table5;
+--------+----------+
| number | username |
+--------+----------+
| 3      | Luo      |
| 3      | Fang     |
+--------+----------+2 rows in set (0.00 sec)
Copy after login

The above is the detailed content of Detailed explanation of MySQL data 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles