SQL language(1)

The SQL language is the database's own language, which provides functions for adding, deleting, modifying, and querying the database.

SQL language usage specification:

  • In the database system, SQL statements are not case sensitive (uppercase is recommended)
  • But strings are often case sensitive.
  • SQL statement can be written in single line or multiple lines, ending with ";"
  • Keywords cannot span multiple lines or be abbreviated. For example: from create drop, etc.
  • Use spaces or indentation to improve the readability of statements
  • Words and sentences are usually located on separate lines for easy editing and improved readability

Database operation

Increase the database:CREATE DATABASE|SCHEMA [IF NOT EXISTS] 'DB_NAME';
CHARACTER SET 'character set name'
COLLATE 'collate name'

  • [DEFAULT] CHARACTER SET: Specify the character set of the database. The purpose of specifying the character set is to avoid garbled characters in the data stored in the database. If you do not specify the character set when creating the database, the system default character set is used.
  • [DEFAULT] COLLATE: Specify the default collation rules for the character set.

MySQL's character set (CHARACTER) and collation (COLLATION) are two different concepts. The character set is used to define
the way MySQL stores strings, and the collation rules define the way to compare strings.

Example:


MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS ydong;
Query OK, 1 row affected (0.00 sec)
#如果ydong数据不存在就创建ydong数据库

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| ydong              |
+--------------------+
5 rows in set (0.01 sec)

View database character set


MariaDB [(none)]> SHOW CREATE DATABASE ydong;
+----------+------------------------------------------------------------------+
| Database | Create Database                                                  |
+----------+------------------------------------------------------------------+
| ydong    | CREATE DATABASE `ydong` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+------------------------------------------------------------------+
如果没有指定默认是latin

Set the character set when creating

MariaDB [(none)]> CREATE DATABASE utf8base  CHARACTER SET utf8;

Delete character set

MariaDB [(none)]> DROP DATABASE ydong;
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| utf8base           |
+--------------------+
5 rows in set (0.00 sec)

View all character sets supported:

MariaDB [(none)]> SHOW  CHARACTER SET;

View all sorting rules supported:

MariaDB [(none)]> SHOW COLLATION;

Select database

MariaDB [(none)]> USE utf8base;
Database changed
MariaDB [utf8base]> 

Naming rules:

  • Must start with a letter
  • Can include numbers and three special characters (# _ $)
  • Do not use MySQL reserved words are words in the grammar, such as select, from, etc.
  • Objects under the same database (Schema) cannot have the same name, that is, the table names in the database cannot be repeated

Table operations

Before table operations, you need to introduce the data type, that is, define how the data is stored. Need to be used in the process of creating a table

There should be relatively appropriate storage rules in each column, such as phone numbers no more than 13 digits and ID card no more than 18 digits. If the set range does not meet the requirements more or less, it is bound to have a certain impact on disk space and performance

Numeric type

MySQL supports all standard SQL numeric data types. These types include strict numeric data types (INTEGER, SMALLINT, DECIMAL, and NUMERIC), and approximate numeric data types (FLOAT, REAL, and DOUBLE PRECISION). The keyword INT is a synonym for INTEGER, and the keyword DEC is a synonym for DECIMAL.

Integer type

As an extension of the SQL standard, MySQL also supports the integer types TINYINT, MEDIUMINT, and BIGINT.

Insert picture description here

The above is the number of bytes occupied by the integer type and its value range.

MySQL also supports the option to specify the display width of integer values ​​in parentheses after this type of keyword (for example, INT(4)). This optional display width is used to fill the width from the left when the display width is less than the specified column width.

For example, in the case of INT(4), if you enter 4, it will automatically fill in 0004, but if you exceed 4 widths but do not exceed the value range, it will still be displayed in full.

All integer types can have an optional (non-standard) attribute UNSIGNED. You can use unsigned values ​​when you want to allow only non-negative numbers in a column and the column requires a larger upper limit value range. That is, the maximum value is doubled, there are no negative numbers, only positive numbers.

Floating point type

The floating-point type has two representations, single-precision float and double-precision double; the fixed-point type DECIMAL is used to store values ​​that must be exact precision, such as currency data.

For floating-point column types, single-precision values ​​use 4 bytes in MySQL, and double-precision values ​​use 8 bytes.

The FLOAT type is used to represent approximate numeric data types. The SQL standard allows the option to specify the precision in bits (but not the exponent range) in the brackets after the keyword FLOAT. MySQL also supports optional precision specifications that are only used to determine storage size. The precision of 0 to 23 corresponds to the 4-byte single precision of the FLOAT column. The precision of 24 to 53 corresponds to the 8-byte double precision of the DOUBLE column.

MySQL allows the use of non-standard syntax: FLOAT (M, D) or REAL (M, D) or DOUBLE PRECISION (M, D). Here, "(M,D)" means that the value shows a total of M digits, and the D digit is behind the decimal point. For example, a column defined as FLOAT(7,4) can be displayed as -999.9999. MySQL performs rounding when saving values, so if you insert 999.00009 in the FLOAT(7,4) column, the approximate result is 999.0001.

The value range of the floating-point number type is M (1~255) and D (1~30, and cannot be greater than M-2), which respectively represent the display width and the number of decimal places. M and D are optional in FLOAT and DOUBLE, FLOAT and DOUBLE types will be saved as the maximum precision supported by the hardware. The default D value of DECIMAL is 0 and M value is 10.

Floating-point storage

type name Explanation storage
float Single precision 4 bytes
double Double precision 8 bytes
DECIMAL Single precision M+2 bytes

The DECIMAL type is different from FLOAT and DOUBLE. DOUBLE is actually stored in the form of a string. The maximum possible value range of DECIMAL is the same as DOUBLE, but the effective value range is determined by M and D. If M is changed and D is fixed, the value range will become larger as M becomes larger.

Remarks: Because of the need for additional space and calculation overhead, you should try to use decimal only when calculating decimals accurately-such as storing financial data. But when the amount of data is relatively large, you can consider using bigint instead of decimal

String

String types refer to CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET.

CHAR and VARCHAR
CHAR(M) are fixed-length character strings. Specify the column length of the character string when defining. When saving, fill in spaces on the right to reach the specified length. M indicates the length of the column, and the range is 0 to 255 characters.

For example, CHAR(4) defines a fixed-length string column with a maximum of 4 characters. When the CHAR value is retrieved, the trailing spaces will be deleted.

VARCHAR(M) is a variable-length character string, M represents the length of the largest column, and the range of M is 0~65535. The maximum actual length of VARCHAR is determined by the size of the longest row and the character set used, and the actual space occupied is the actual length of the string plus 1.

For example, VARCHAR(50) defines a character string with a maximum length of 50. If the inserted character string has only 10 characters, the actual stored character string is 10 characters and an end character. The trailing spaces of VARCHAR are retained when the value is saved and retrieved.

Insert picture description here

text

TEXT columns are treated as non-binary strings (character strings). The TEXT column has a character set, and the values ​​are sorted and compared according to the collation rules of the character set. TEXT characters can have varying lengths. Similar to VARCHAR

There are 4 types of TEXT: TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT. Different TEXT types have different storage space and data length.

  • TINYTEXT represents a TEXT column with a length of 255 (28-1) characters.
  • TEXT represents a TEXT column with a length of 65535 (216-1) characters.
  • MEDIUMTEXT represents a TEXT column with a length of 16777215 (224-1) characters.
  • LONGTEXT represents a TEXT column with a length of 4294967295 or 4GB (232-1) characters.

ENUM

ENUM is a string object whose value comes from a list of values ​​explicitly enumerated in the column specification when the table is created. That is, 1 choice more

SET

SET is a string object, which can have zero or more values, and its value comes from a list of allowed values ​​specified when the table was created. When specifying a SET column value that includes multiple SET members, use a comma (',') to separate each member. So the SET member value itself cannot contain commas.
SET can have up to 64 different members.
When the table is created, the trailing space of the SET member value will be automatically

Date and time

Date time type

  • date date '2008-12-2'
  • time time '12:25:36'
  • datetime datetime '2008-12-2 22:06:44'
  • timestamp automatically stores record modification time
  • YEAR(2), YEAR(4):
    The time data in the year timestamp field will be automatically refreshed when other fields are modified. This data type field can store the last modified time of this record

Modifier

All types

  • NULL data column can contain NULL values
  • NOT NULL data columns are not allowed to contain NULL values
  • DEFAULT default value
  • PRIMARY KEY primary key, not allowed to be empty, and unique
  • UNIQUE KEY unique key
  • CHARACTER SET name specifies a character set

Numerical

  • AUTO_INCREMENT automatically increments, applicable to integer types
  • UNSIGNED unsigned

Table creation

There are three ways to create a table
1) Create directly,CREATE TABLE

MariaDB [ydong]> CREATE TABLE TEST1 (name VARCHAR(10));

2) Create by querying an existing table; the new table will be directly inserted into the data from the query

MariaDB [ydong]> CREATE TABLE IF NOT EXISTS test2 SELECT * FROM mysql.user;
MariaDB [ydong]> SELECT user,host,password FROM test2;
+------+-----------+----------+
| user | host      | password |
+------+-----------+----------+
| root | localhost |          |
| root | ansible   |          |
| root | 127.0.0.1 |          |
| root | ::1       |          |
|      | localhost |          |
|      | ansible   |          |
+------+-----------+----------+

3) Created by copying the table structure of the existing table, but not copying the data

MariaDB [ydong]> CREATE TABLE IF NOT EXISTS test3 LIKE ydong.test2;

Create a complete table with student id, student name, and contact information.

MariaDB [ydong]> CREATE TABLE IF NOT EXISTS students (id INT(50) UNSIGNED PRIMARY KEY AUTO_INCREMENT,name VARCHAR(10) NOT NULL , phone INT(13));
MariaDB [ydong]> desc students;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(50) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10)      | NO   |     | NULL    |                |
| phone | int(13)          | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+

Table operations

delete:DROP TABLE [IF EXISTS] 'tbl_name';

MariaDB [ydong]> DROP TABLE TEST1;

Modify field

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name [alter_specification [, alter_specification] ...] [partition_options]
You can use HELP ALTER to view detailed usage

1)
Add fields:ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name ]

MariaDB [ydong]> ALTER TABLE students ADD address VARCHAR(100) AFTER phone;

2)
Modify fields:CHANGE [COLUMN] old_col_name new_col_name column_definition [FIRST|AFTER col_name]

MariaDB [ydong]> ALTER TABLE students CHANGE address teachers VARCHAR(10);
Query OK, 0 rows affected (0.03 sec)               
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [ydong]> DESC students;
+----------+------------------+------+-----+---------+----------------+
| Field    | Type             | Null | Key | Default | Extra          |
+----------+------------------+------+-----+---------+----------------+
| id       | int(50) unsigned | NO   | PRI | NULL    | auto_increment |
| name     | varchar(10)      | NO   |     | NULL    |                |
| phone    | int(13)          | YES  |     | NULL    |                |
| teachers | varchar(10)      | YES  |     | NULL    |                |
+----------+------------------+------+-----+---------+----------------+

3)

Modify table name

MariaDB [ydong]> ALTER TABLE test2 RENAME test4;

4)
Delete the field name


	
MariaDB [ydong]> ALTER TABLE students DROP teachers;
MariaDB [ydong]> DESC students;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(50) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10)      | NO   |     | NULL    |                |
| phone | int(13)          | YES  |     | NULL    |                |

Data manipulation DML

INSERT

You can select the field value to be inserted. If you don't specify it, all fields will have values ​​inserted. Insert one or more rows of data at a time

Simple writing:INSERT tbl_name [(col1,...)] VALUES (val1,...), (val21,...)

MariaDB [ydong]> INSERT students (id,name,phone) VALUES (1,'xiaohong',123),(2,'xiaoming',321);
MariaDB [ydong]> select * from students;
+----+----------+-------+
| id | name     | phone |
+----+----------+-------+
|  1 | xiaohong |   123 |
|  2 | xiaoming |   321 |
+----+----------+-------+

You can also use the information in other tables to insert data into the table, but pay attention to the correspondence

MariaDB [ydong]> INSERT students(name,phone) SELECT user,max_questions from mysql.user;

UPDATE

Update data, but there must be restrictions when updating, otherwise all data will be updated.

MariaDB [ydong]> UPDATE students SET name='xiaohuang';
Query OK, 8 rows affected (0.01 sec)
Rows matched: 8  Changed: 8  Warnings: 0

MariaDB [ydong]> select * from students;
+----+-----------+-------+
| id | name      | phone |
+----+-----------+-------+
|  1 | xiaohuang |   123 |
|  2 | xiaohuang |   321 |
|  3 | xiaohuang |     0 |
|  4 | xiaohuang |     0 |
|  5 | xiaohuang |     0 |
|  6 | xiaohuang |     0 |
|  7 | xiaohuang |     0 |
|  8 | xiaohuang |     0 |
+----+-----------+-------+
8 rows in set (0.00 sec)

Then you need to add where restrictions to control the update of a field,


MariaDB [ydong]> UPDATE students SET name='xiaoming',phone=666 WHERE id=3;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [ydong]> SELECT * FROM students;
+----+-----------+-------+
| id | name      | phone |
+----+-----------+-------+
|  1 | xiaohuang |   123 |
|  2 | xiaohuang |   321 |
|  3 | xiaoming  |   666 |
|  4 | xiaohuang |     0 |
|  5 | xiaohuang |     0 |
|  6 | xiaohuang |     0 |
|  7 | xiaohuang |     0 |
|  8 | xiaohuang |     0 |
+----+-----------+-------+
8 rows in set (0.01 sec)

When misoperation is performed without adding where restrictions, the destructive power is huge. MySQL uses a security option for this kind of problem --safe-update. Or write it in the configuration file.

[root@ansible ~]# cat /etc/my.cnf.d/client.cnf 
[client]
safe_updates


MariaDB [(none)]> show variables like '%safe_updates%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| sql_safe_updates | ON    |
+------------------+-------+

mariaDB [ydong]> UPDATE students SET name='ydong';
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column

DELETE

Delete the data in the table

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]


ORDER BY 子句:可选项。表示删除时,表中各行将按照子句中指定的顺序进行删除。
WHERE 子句:可选项。表示为删除操作限定删除条件,若省略该子句,则代表删除该表中的所有行。
LIMIT 子句:可选项。用于告知服务器在控制命令被返回到客户端前被删除行的最大值。

删除不是在安全模式下,但是生产环境中绝不可以这样
MariaDB [ydong]> DELETE FROM test4;
Query OK, 6 rows affected (0.02 sec)

MariaDB [ydong]> SELECT * FROM test4;
Empty set (0.00 sec)
数据全部清除

MariaDB [ydong]> DELETE FROM students WHERE id<4;
表示ID前三行数据全部删除


Guess you like

Origin blog.csdn.net/qq_44564366/article/details/104357470