MySQL Tutorial 1.5

MySQL creates data table

Creating a MySQL data table requires the following information:

  • Table Name
  • table field name
  • Define the data type of each table field

grammar

The following is the general SQL syntax for creating MySQL data tables:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    ...
);
  • table_name is the name of the table you want to create.
  • column1column2, ... are the column names in the table.
  • datatype is the data type of each column.

The following is a specific example to create a user table users:

Example

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    birthdate DATE,
    is_active BOOLEAN DEFAULT TRUE
);

Example analysis:

  • id: User id, integer type, self-increasing, used as primary key.
  • username: Username, variable-length string, not allowed to be empty.
  • email: User email, variable length string, not allowed to be empty.
  • birthdate: User's birthday, date type.
  • is_active: Whether the user has been activated, Boolean type, default value is true.

The above is just a simple example, using some common data types including INT, VARCHAR, DATE, and BOOLEAN. You can choose different data types according to actual needs. The AUTO_INCREMENT keyword is used to create an auto-increasing column, and PRIMARY KEY is used to define the primary key.

If you want to specify the data engine, character set and collation when creating a table, you can use CHARACTER SET and  COLLATE Clause:

Example

CREATE TABLE mytable (
    id INT PRIMARY KEY,
    name VARCHAR(50)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

The above code creates a table using the utf8mb4 character set and the utf8mb4_general_ci collation.

In the following example we will create the data table runoob_tbl in the RUNOOB database:

Example

CREATE TABLE IF NOT EXISTS `runoob_tbl`(
   `runoob_id` INT UNSIGNED AUTO_INCREMENT,
   `runoob_title` VARCHAR(100) NOT NULL,
   `runoob_author` VARCHAR(40) NOT NULL,
   `submission_date` DATE,
   PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Example analysis:

  • If you don’t want the field to benull, you can set the field’s attribute to NOT NULL , as shown in the runoob_title and runoob_author fields in the above example, if the data entered in this field is empty when operating the database, an error will be reported.

  • AUTO_INCREMENT defines a column as an auto-increment attribute, generally used for primary keys, and the value will automatically increase by 1.
  • The PRIMARY KEY keyword is used to define the column as the primary key. You can use multiple columns to define the primary key, separated by commas , .
  • ENGINE sets the storage engine, CHARSET sets the encoding.


Create table via command prompt

MySQL data tables can be easily created through the mysql> command window.

You can use the SQL statement CREATE TABLE to create a data table.

Example

The following is an example of creating a data table runoob_tbl:

Example

root@host# mysql -u root -p
Enter password:*******
mysql> USE RUNOOB;
DATABASE changed
mysql> CREATE TABLE runoob_tbl(
   -> runoob_id INT NOT NULL AUTO_INCREMENT,
   -> runoob_title VARCHAR(100) NOT NULL,
   -> runoob_author VARCHAR(40) NOT NULL,
   -> submission_date DATE,
   -> PRIMARY KEY ( runoob_id )
   -> )ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 ROWS affected (0.16 sec)
mysql>

Note:MySQL command terminator is semicolon ; .

Note: -> is a newline identifier, do not copy it.

Create a data table using PHP script

You can use PHP's mysqli_query() function to create a data table from an existing database.

This function takes two parameters and returns TRUE if the execution is successful, otherwise it returns FALSE.

grammar

mysqli_query(connection,query,resultmode);
parameter describe
connection Required. Specifies the MySQL connection to use.
query Required, specifies the query string.
resultmode

Optional. a constant. Can be any of the following values:

  • MYSQLI_USE_RESULT (use this if you need to retrieve large amounts of data)
  • MYSQLI_STORE_RESULT (default)

Example

The following example uses a PHP script to create a data table:

Create data table

<?php $dbhost = 'localhost'; // mysql server host address $dbuser = 'root'; // mysql user name $dbpass = '123456' ; // mysql username and password $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Connection failed: ' . mysqli_error($conn)); } echo 'Connection successful<br />'; $sql = "CREATE TABLE runoob_tbl( ". "runoob_id INT NOT NULL AUTO_INCREMENT, ". "runoob_title VARCHAR(100) NOT NULL, ". "runoob_author VARCHAR(40) NOT NULL, ". "submission_date DATE, ". "PRIMARY KEY ( runoob_id ))ENGINE=InnoDB DEFAULT CHARSET=utf8; "; mysqli_select_db( $conn, 'RUNOOB' ); $retval = mysqli_query( $conn, $sql ); if(! $retval ) { die('Data table creation failed: ' . mysqli_error($conn) ); } echo "Data table created successfully\n"; mysqli_close($conn); ?>

After successful execution, you can view the table structure through the command line:

Organizing notes from netizens

When creating a MySql table, the symbol ` outside the table name and field name is not a single quotation mark, but an anti-single quotation mark in the English input method state, which is the ~ button under the esc button in the upper left corner of the keyboard. This is a big mistake.

Backticks are symbols introduced to distinguish MySql keywords from ordinary characters. Generally, backticks are used in table names and field names.

 

MySQL field attributes should be set to NOT NULL whenever possible

Unless you have a very specific reason to use NULL values, you should always keep your fields NOT NULL. This may seem a bit controversial, please read on.

1, First of all, we need to understand the concepts of null value "" and NULL:

  •  1) Null values ​​do not take up space
  •  2) NULL in MySQL actually takes up space

The so-called NULL means nothing, not even \0 , \0 is the terminator in the string, but it takes up space in the physical memory, equal to one byte, and NULL does not even have this byte.

2, Secondly, there is a strict distinction in the database. Any number calculated with NULL will be NULL. To determine whether the value is equal to NULL, you cannot simply use =, but use IS NULL keyword.

3.The field col1 of the database is set to NOT NULL, which only means that the field cannot be NULL, that is, only when:

INSERT INTO table1(col1) VALUES(NULL);

In this case, the database will report an error, and:

INSERT INTO table1(col1) VALUES('');

No error will be reported.

(If the field is an auto-increment ID, the first sentence will not report an error. This does not mean that it can be NULL, but the database system will fill in the default value set according to the ID, or if it is an auto-increment field, it will automatically add a default value. operate.)

4, Columns containing null values ​​are difficult to optimize queries, and NULL values ​​will not be stored when indexing the table, so if the indexed field can be NULL, the indexed Efficiency will drop a lot. Because they make indexes, index statistics, and comparison operations more complex. You should replace null values ​​with 0, a special value, or an empty string.

5, When performing a joint table query, such as LEFT JOIN table2, if there is no record, the found table2 fields will be null. If some fields in table2 can themselves be null, then unless the fields that are not null in table2 are found, it will be difficult to distinguish whether there are no associated records or other situations.

MySQL storage engine InnoDB and MyISAM

ENGINE = innodb

The storage engine is innodb. innodb is the first data storage engine on MySQL to provide foreign key constraints. In addition to providing transaction processing, InnoDB also supports row locks, providing the same consistent non-locked reading as Oracle, which can increase the number of concurrent reading users and Improves performance without increasing the number of locks. InnoDB is designed to maximize performance when processing large volumes of data, and its CPU utilization is the most efficient of any other disk-based relational database engine.

InnoDB is a complete database system placed in the MySQL backend. InnoDB has its own buffer pool that can buffer data and indexes. InnoDB also stores data and indexes in a table space, which may contain several files. This is completely the same as the MyISAM table. Differently, in MyISAM, tables are stored in separate files, and the size of InnoDB tables is only limited by the size of the operating system file, which is generally 2GB.

For more information, please refer to:Six major differences between MySQL storage engine InnoDB and MyISAM 

 

MySQL delete data table

Deleting a data table in MySQL is very easy, but you must be very careful when deleting a table, because all data will disappear after executing the delete command.

grammar

The following is the general syntax for deleting MySQL data tables:

DROP TABLE table_name ;

Delete data table in command prompt window

The SQL statement to delete the data table in the mysql> command prompt window is  DROP TABLE :

Example

The following example deletes the data table runoob_tbl:

root@host# mysql -u root -p
Enter password:*******
mysql> use RUNOOB;
Database changed
mysql> DROP TABLE runoob_tbl;
Query OK, 0 rows affected (0.8 sec)
mysql>

Delete data table using PHP script

PHP uses the mysqli_query function to delete MySQL data tables.

This function takes two parameters and returns TRUE if the execution is successful, otherwise it returns FALSE.

grammar

mysqli_query(connection,query,resultmode);
parameter describe
connection Required. Specifies the MySQL connection to use.
query Required, specifies the query string.
resultmode

Optional. a constant. Can be any of the following values:

  • MYSQLI_USE_RESULT (use this if you need to retrieve large amounts of data)
  • MYSQLI_STORE_RESULT (default)

Example

The following example uses a PHP script to delete the data table runoob_tbl:

Delete database

<?php $dbhost = 'localhost'; // mysql server host address $dbuser = 'root'; // mysql user name $dbpass = '123456' ; // mysql username and password $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Connection failed: ' . mysqli_error($conn)); } echo 'Connection successful<br />'; $sql = "DROP TABLE runoob_tbl"; mysqli_select_db( $conn, 'RUNOOB' ); $retval = mysqli_query( $ conn, $sql ); if(! $retval ) { die('Data table deletion failed: ' . mysqli_error($conn)); } echo "Data table deletion successful\n"; mysqli_close( $conn); ?>

After successful execution, we use the following command and the runoob_tbl table will no longer be visible:

mysql> show tables;
Empty set (0.01 sec)

Organizing notes from netizens

To delete data in the table, use delete. The format is:

delete from table name where delete condition;

Example: Delete the record named Zhang San in the student table.

delete from  student where  T_name = "张三";

Clear the data in the table and save the table structure, use truncate. The format is:

truncate table table name;

Example: Clear all data in the student table.

truncate  table  student;

To delete a table, use drop, but nothing will be left. The format is:

drop table table name;

Example: Delete the student table.

drop table student;

1. When you no longer need the table, use drop;

2. When you still want to keep the table but delete all records, use truncate;

3. When you want to delete some records, use delete.

 

Several situations in which MySQL deletes tables:

1. drop table table_name: delete all data and table structure of the table and immediately release disk space, whether it is Innodb or MyISAM;

Example, delete the student table:

drop table student;

2. Truncate table table_name: delete all data in the table, retain the table structure, and immediately release disk space, whether it is Innodb or MyISAM;

Example, delete the student table:

truncate table student;

3. delete from table_name: delete all the data in the table, and the table structure remains unchanged. For MyISAM, the disk space will be released immediately, while for InnoDB, the disk space will not be released;

Example, delete the student table:

delete from student;

4. delete from table_name where xxx: Conditional deletion, the table structure remains unchanged, and neither innodb nor MyISAM will release disk space;

Example, delete the data named "Zhang San" in the student table:

delete from student where T_name = "张三";

5. After the delete operation, using optimize table table_name will immediately release disk space, whether it is innodb or myisam;

Example, delete the data named "Zhang San" in the student table:

delete from student where T_name = "张三";

Example, release the table space of the student table:

optimize table student;

6. Although the disk space is not released after deleting from the table, this space can still be used the next time data is inserted.

Three ways to delete data from MySQL database:

delete from table where

Directly delete a row of data in the table, and at the same time save the row's deletion operation as a transaction record in the log for rollback operation. Therefore, delete takes up more resources than truncate, and the data space is not released because it needs to be rolled back. It can operate on tables and views.

truncate table

Deleting all the data from the table at once (freeing the data pages used to store the table data to delete the data) does not record the individual deletion operations in the log (only recording the page release in the transaction log), so it cannot Rollback, data cannot be restored, and the deletion trigger related to the table will not be activated during the deletion process, occupying less resources and being faster. The data space will be released, and the space occupied by this table and index will be restored to its original size. Only tables without associated views can be manipulated.

truncate table cannot be used on tables that participate in indexed views.

drop table

What is deleted is the entire table, including the table structure, data, and definitions. Erase permanently and free up space. It can operate on tables and views. Since TRUNCATE TABLE is not recorded in the log, it cannot activate triggers. For tables referenced by foreign key constraints, truncate table cannot be used. Instead, a delete statement without a where clause should be used.

 

Guess you like

Origin blog.csdn.net/SHADOW_xhx/article/details/134761834