Database principle and application-MySQL data definition and operation actual combat-study notes

#Author: Kearney
#Contents: DataBase System Theory
#Time: 2020

The full text is 3704 words, how to learn without patience. Aoli give it!

Introduction

The installation and connection of the database is beyond the scope of this article: please search and master the installation and connection methods of the database.

This article uses MyQSL as an example. Some related statements in the SQL statement examples are also listed for understanding. Not the main function statement.

The SQL statements in MySQL are not sensitive to the case of keywords, but many developers prefer to capitalize keywords, and use lowercase for table names and field names. If you develop this habit, scripts written later will be easier to read and maintain. .

Principle and Application of Database

Create database

The sql statement uses a semicolon as the end symbol, and is not case sensitive

mysql -u root -p	#以root账户登录数据库,井号“#”后面的内容为注释
					
create database TestDb;		#创建数据库,数据库名为 TestDb

show databases;	#查看MySQL中已存在的数据库,参考语句

Create table

use TestDb;		#选中数据库 TestDb,表示接下来的操作在 TestDb中进行
#若不提前选中数据库而直接建表,则会报错ERROR 1046

create table user(		#在 TestDb中创建表,表名为 user
    id INT,					#每个字段之间用英文逗号隔开
    username VARCHAR(32),
    password VARCHAR(32),
    phone VARCHAR(11)		#!!!这里是没有逗号的哟
);

#下面的内容仅供学习,不是建表必备操作
show tables;	#查看当前数据库中存在的表
DESCRIBE user;	#查看表user的结构,可以简写为 DESC user;
drop table user;	#删除表,仅供参考,不得已不使用的命令

The structure of the created table is as follows (much like an Excel table):

Field Name type of data Remarks
id INT User ID
username VARCHAR(32) username
password VARCHAR(32) password
phone VARCHAR(11) cellphone number

INT type stores numbers, VARCHAR() is a character type, and the maximum length of characters in parentheses

Add primary key constraint

The primary key constraint (Primary Key Constraint)requires the data in the primary key column to be unique and it is not allowed to be empty. The primary key can uniquely identify each record in the table, just like our ID.

The primary key of a table can be multiple or single.

Specify the primary key when building the table

Specify the primary key while defining the column

create table user(		
    id INT primary key,		#指定id为主键
    username VARCHAR(32),
    password VARCHAR(32),
    phone VARCHAR(11)
);

Specify the primary key after defining all columns

create table user(		
    id INT ,		
    username VARCHAR(32),
    password VARCHAR(32),
    phone VARCHAR(11)primary key(id)#指定id为主键
#    primary key(id,username)#指定id和username为主键,不同字段之间用逗号隔开
);

Modify the structure of the table to specify the primary key

alter table user add primary key (id);  	#此时id在表里面必须是第一列

Foreign key constraint

The foreign key (foreign key) is the primary key in another table . Used to maintain data consistency and integrity.

The foreign key type must be set with the corresponding primary key type.

If the field to be deleted contains a foreign key, the deletion fails and an error is reported, and the foreign key constraint must be deleted first.

CONSTRAINT 外键名 FOREIGN KEY 字段名 REFERENCES 主表名(主键名)
CREATE table t_class(
id INT PRIMARY KEY,	#主键,班级id
NAME VARCHAR(22)
);

CREATE table t_student(
id INT PRIMARY KEY,
NAME VARCHAR(22),
classId INT,	#为班级id添加外键
CONSTRAINT fk_stu_class1 FOREIGN KEY (classId) REFERENCES t_class(id)
);	#外键名是任意的,外键在另一个表中必须是主键!!!

Common constraints

create table t_user(
id int primary key auto_increment,
username varchar(32) not null unique,
sex varchar(4) DEFAULT '男' 
);

To add two or more constraints to a field, separate the constraints with spaces.

Unique constraint

The unique constraint (Unique Constraint)requires that the data in the column is unique, and it is allowed to be empty, but there can be only one null value. When entering data in a column with unique constraints, an error will be reported.

When adding this constraint, you only need to add keywords after the field name UNIQUE

The primary key comes with a unique constraint halo, which is often used on other non-primary keys, such as email and mobile phone number (some registration pages are self-evident)

Non-empty constraint

After adding the non-null constraint to a field, the database will check whether the input of the field is empty when inserting data into the table. If it is empty, the data insertion fails and an error is reported. Commonly used in some required fields, such as mobile phone number in real-name authentication

When adding this constraint, you only need to add keywords after the field nameNOT NULL

Default constraint

Sometimes we want some data to be the default value. For example, the second-level score in the student's score sheet is P (manual dog head) by default, so that only a small number of students who have missed courses can be modified.

When adding this constraint, you only need to add keywords after the field name DEFAULT

  • If you add a string type default value, use English single quotation marks
  • If you want to add the Chinese default value, you need to addDEFAULT CHARSET=utf8;

Automatic increase

This is easier to understand, such continuous data as student number and work number.

When adding this constraint, you only need to add keywords after the field name AUTO_INCREMENT. By default, the initial value and increment are both1

View table structure

DESCRIBEYou can view the field information of the table, including: field name, field data type, whether it is a primary key, whether there is a default value, etc.

  • NULL: This column indicates whether the stored NULLvalue;
  • Key: Indicates whether the column has been indexed;
  • PRI: Indicates that the column is part of the primary key of this table;
  • UNI: Indicates that the column is UNIQUEpart of the index;
  • MUL: Indicates that a given value can appear multiple times in the column;
  • Default: Indicates whether the column has a default value, and if so, what is the value;
  • Extra: Indicates additional information related to a given column that can be obtained.

View the detailed structure of the data table: In addition to returning to us the detailed statement written when building the table, you can also view the storage engine and character encoding.

SHOW CREATE TABLE 表名;

I think the layout of the returned result is a bit messy. After we add it \G, the effect will be improvedSHOW CREATE TABLE 表名 \G;

Modify the structure of the table

Modify table name

ALTER TABLE 旧表名 RENAME 新表名;

Modify field name

ALTER TABLE 表名 CHANGE 旧字段名 新字段名 新数据类型;

The new data type cannot be empty! ! ! It can be the same as before, or it can be different.

Modify field data type

ALTER TABLE 表名 MODIFY 字段名 数据类型;

Add field

ALTER TABLE 表名 ADD 新字段名 数据类型 [约束条件] [FIRST|AFTER] 已存在字段名;

If you do not [FIRST|AFTER]specify the position, MySQLthe new field will be added to the last column of the table by default when adding a field

If we want to add a new field in the first column, we only need to make FIRSTa position description. If you want to specify to add a new field after a certain column, you only need to make AFTERa position description. If you specify it in front of a certain column, an error will be reported! ! !

Delete field

ALTER TABLE 表名 DROP 字段名;

Modify the arrangement position of the field

ALTER TABLE 表名 MODIFY 字段1 数据类型 FIRST|AFTER 字段2;

When only FIRSTthe position description is made, field 1 will be transferred to the first column.

Delete the foreign key constraint of the table

ALTER TABLE 表名 DROP FOREIGN KEY 外键约束名;

Insert data

Insert data for all fields of the table

INSERT INTO 表名 (字段名) VALUES (内容);

Multiple fields and contents are separated by commas, and character contents are enclosed by a pair of single quotation marks. The content must correspond to the specified field order. If you do not fill in the field name, insert the corresponding data in the order of the fields in the table.

Insert multiple records into the table at the same time

INSERT INTO 表名 (字段名) VALUES (内容1),(内容2),(内容3);

Update the content specified in the table

UPDATE 表名 SET 字段名1 = 内容1, 字段名2 = 内容2, 字段名3 = 内容3 WHERE 过滤条件;

The number of fields depends on the update requirements, and as many as one update is required

Delete the specified row in the table

DELETE FROM 表名 WHERE 条件语句;

The conditional statement specifies what to delete, if omitted where 条件语句;, all rows are deleted.

TRUNCATE TABLE 表名;It can also be used to delete all records in the table. But unlike DELETE, the TRUNCATE TABLE statement directly deletes the table, not the contents of the table. After the deletion, a table is recreated. So its execution speed will be faster than DELETE statement.

Inquire

SELECT 字段名1,字段名2 FROM 表名;

SELECT 字段名1,字段名2 FROM 表名 WHERE 条件语句;

Multiple field names are separated by commas. To query all fields, *replace all field names. where is used to filter the content that needs to be queried.

Comparison operator

Operator Description
> more than the
>= greater than or equal to
= equal
!= or <> not equal to
< Less than
<= less than or equal to

in

SELECT 字段名 FROM 表名 WHERE 字段名 IN (n1,n2,n3,...);

SELECT 字段名 FROM 表名 WHERE 字段名 NOT IN (n1,n2,n3,...);

IN is used to filter the content that needs to be queried; if it is a number in parentheses, it must be a INTformat. In fact, when the content of IN is small, you can use where field name=n1 or field name=n1 instead,

BETWEEN AND

SELECT 字段名 FROM 表名 WHERE 字段名 BETWEEN n1 AND n2;

SELECT 字段名 FROM 表名 WHERE 字段名 NOT BETWEEN n1 AND n2;

Closed interval: The filtering range includes n1 and n2.

like

Use wildcards %or _fuzzy matching data content

The percent sign wildcard %can match characters of any length, even including zero characters; the underscore wildcard _can only match 1个characters fuzzy (a space is also counted as one character), and the two can be matched with each other, and the position is flexible.

SELECT 字段名 FROM 表名 WHERE 字段名 LIKE '字符%';·

SELECT 字段名 FROM 表名 WHERE 字段名 LIKE '字符_';

IS NULL

Filter the result of a field in the result is/not a null value NULL.

SELECT 字段名 FROM 表名 WHERE 字段名 IS [NOT] NULL;

DISTINCT

Remove duplicate rows in the selected results

SELECT DISTINCT 字段名 FROM 表名;

AND OR

SELECT 字段名 FROM 表名 WHERE 表达式1 AND 表达式2 [AND/OR] 表达式3 ;

Use logical relationships to filter results with multiple filter conditions for different fields (for example, find me who is above 170 and weighs less than 140). It is better to use or if there are multiple conditions in the same field.

LIMIT

Used to limit the number of query results.

SELECT 字段名 FROM 表名 LIMIT [OFFSET,] 记录数;

Parameter Description:

  • The first parameter OFFSET,, optional parameter, indicates the offset , if the default value is not specified 0, it means starting from the first record of the query result, if the offset is 1, then starting from the second record in the query result , And so on.
  • The second parameter, the number of records, indicates the number of query results returned.

Sort ORDER BY

SELECT 字段名 FROM 表名 ORDER BY 字段名1 [ASC[DESC]];

Display in ascending order (ASE) or descending order (DESC) according to the field name 1, only ORDER BY 字段名1without specifying the order, the ascending order is used by default.

Group query GROUP BY

Query is each group a record first appears .

SELECT 字段名 FROM 表名 GROUP BY 字段名;

AS

Used to alias the table or column in the query result

Inner join query

  • Only the rows that meet the join conditions in the two tables are combined as a result set, which is called an inner join;
  • Keywords:[inner] join ... on

表1 [inner] join 表2 on 表1.字段=表2.字段

Take out each record from Table 1, and go to Table 2 to match all the records. The matching must be that a certain condition is the same in Table 1 and Table 2 before the result is finally retained, otherwise it is not retained. The inner keyword can be omitted; on represents the connection condition: the condition field represents the same business meaning, in most cases it is the primary and foreign key relationship in the two tables.

Such as: query the name of the student's corresponding class, and it will not be found if there is no class.

Outer join query

  • Take a certain table as the main one, take out all the records in it, and then each one is connected with another table, regardless of whether it can match the conditions, it will eventually be retained. It can be matched and reserved correctly; if it cannot be matched, the fields of other tables are blank ( null), which is called outer join.
  • Outer join query is divided into left outer join query and right outer join query;
  • 表1 left/right [outer] join 表2 on 表1.字段=表2.字段
  • Left outer join: On the basis of the inner join, it also contains all the data rows that do not meet the conditions in Table 1, and fill in the column of Table 2 with NULL; right outer join: On the basis of the inner join, it also includes Table 2 All data rows that do not meet the conditions are filled with NULL in column 1 of Table 1.

Such as: query the name of the corresponding course for college students, the result of the course that has not selected the course is NULL or the result of the student who is not selected for a certain course is NULL.

Compound query

Combine the above. . . Operation together is as fierce as a tiger.

Subquery

Use the result selected by SELECT as the data source of another SELECT

SELECT * FROM t1 WHERE col1=(SELECT col2 FROM t2);

Subqueries are nested within the query and must always appear in parentheses. Subqueries can be divided into four categories:

  • Scalar subquery: returns a scalar with a single value, the simplest form;
  • Liezi query: returns the result set is Nline one;
  • Row subquery: Return result set is a line of Ncolumns;
  • Table subquery: The returned result set is NOK Ncolumn.

Keyword subquery ALL ANY SOME IN

ALL

ALL must be connected to the back of a comparison operator, represents the sub-query returns all values comparison are TRUEreturned TRUE. Commonly used in looking bigger than the biggest, smaller than the smallest

ANY SOME

ANYUsed in conjunction with the comparison operator, it means that it is returned when compared with any value returned by the subquery . Yes , aliases are generally used less. Often used to find larger than the smallestTRUETRUESOMEANY

IN

  • INMeans whether the specified value is in this set, if it is, it will be returned TRUE; otherwise, it will be returned FALSE, the same as IN(item 1, item 2,...);
  • INIs = ANYan alias, both the same, but NOT INthe alias is not <> ANYbut <> SOME.

function

AVG average

SELECT AVG(列名) FROM 表明;

Error Collection

ERROR 1046 (3D000): No database sleected

No database selected, use 数据库名称

Guess you like

Origin blog.csdn.net/weixin_43031092/article/details/106032052