Support crazy god teacher’s learning platform: www.kuangStudy.com

MySQL01: Introduction to MySQL

Why learn databases

1. Job skill requirements

Now the world, the data of the world

3. Methods of storing data

4. How to save a large amount of data for a long time in programs and websites?

Database is almost the core of a software system.

What is a database

DataBase (DB)

Concept: an organized, shareable collection of large amounts of data stored in a computer for a long time, a data “warehouse”

Function: save, and can safely manage data (such as: add, delete, change, check, etc.), reduce redundancy…

Database Overview:

  • Relational database (SQL)
    • MySQL, Oracle, SQL Server, SQLite, DB2,…
    • Relational databases use foreign key associations to establish relationships between tables
  • Non-relational database (NOSQL)
    • Redis, MongoDB…
    • Non-relational databases usually store data as objects in the database, and the relationship between objects is determined by the properties of each object itself

What is a DBMS

DataBase Management System

Database management software, scientific organization and storage of data, efficient access and maintenance of data

Why do you say that?

Because MySQL is supposed to be a database management system.

Introduction of MySQL

Concept: is a popular open source, free relational database

History: Developed by MySQL AB in Sweden, it is currently a product of Oracle.

Features:

  • Free, open source database
  • Small and functional
  • Easy to use
  • It can run on Windows or Linux
  • Can be suitable for small, medium and even large web applications

Website: www.mysql.com/

MySQL installation

We suggest that you use a compressed version, quick installation, convenient. Not complicated.

Software download

Mysql5.7 64-Bit download address:

Dev.mysql.com/get/Downloa…

If the computer is 64-bit, download it and use the 64-bit version!

Installation steps

1. Download the ZIP package.

D: Environment\mysql-5.7.19 D: Environment\mysql-5.7.19

Add environment variables: My Computer -> Properties -> Advanced -> Environment Variables

Select PATH and add the bin folder below your mysql installation fileCopy the code

4. Edit the my.ini file and pay attention to the replacement path

[mysqld]
basedir=D:\Program Files\mysql-5.7\
datadir=D:\Program Files\mysql-5.7\data\
port=3306
skip-grant-tables
Copy the code

5, start CMD in admin mode, switch to bin directory in mysql, and type mysqld — install

Mysqld –initialize — insecure –user=mysql to initialize the data file

Mysql -u root -p mysql -u root -p

8. Change the root password

update mysql.user set authentication_string=password('123456') where user='root'and Host = 'localhost';
Copy the code

9. Refresh permissions

flush privileges;
Copy the code

Ini file to delete skip-grant-tables

11. Restart mysql to work normally

net stop mysql
net start mysql
Copy the code

12, the connection test appears the following results on the installation

Step by step, there is no problem in theory.

If you have installed before and now need to reinstall, be sure to clean the environment.

Okay, so we’re all set up here, because we’re new, so we’re not going to learn commands.

Here’s a tool I recommend: SQLyog.

Even with visual tools, but the basic DOS naming we still want to remember!

SQLyog

You can manually manage the MySQL database

Features: simple, easy to use, graphical

Do the following yourself using the SQLyog administration tool:

  • Connect to the local MySQL database
  • Create MySchool database
    • field
    • GradeID : int(11) , Primary Key (pk)
    • GradeName : varchar(50)
    • Database name MySchool
    • Create a new database table (grade)

You can see the statements for the corresponding database operations in the history.

Connecting to a Database

The MySQL command window is displayed

  • Go to the installation directory \mysql\bin in the DOS command line window
  • Environment variables can be set, set the environment variables, can be opened in any directory!

Mysql -h server host address -u username -p user password

Note: -p cannot be followed by a space, otherwise it will be regarded as the content of the password, resulting in login failure!

A few basic database operation commands:

update user set password=password('123456')where user='root'; Change password Flush PRIVILEGES; Update database show databases; Display all database use dbname; Open a database show tables; Describe user; Mysql > create database name; Create database use databasename; Select database exit; Exit the Mysql? Command keywords: Ask for help -- indicates a commentCopy the code

MySQL02: Database operation

Structured query statement classification

Database operations

The command line operates the database

Create database: create database [if not exists] Specifies the name of the database.

Drop database: drop database [if exists] Specifies the name of the database.

Run the show databases command to view databases.

Use the database name.

Comparison tools manipulate databases

Learning methods:

  • Learn from statements automatically generated by the SQLyog tool
  • Words in fixed grammar need to be memorized

Create table

A type of DDL with the syntax:

The create table (if not the exists] ` table name ` (' field name 1 column type [properties] [index] [note], 'the field name 2 column type [properties] [index] [note], #... Column type [attribute][index][comment])[table type][table character set][comment];Copy the code

Note: Backquotes are used to distinguish MySQL reserved words from ordinary characters (the key below esc).

Data values and column types

Column type: Specifies the type of data stored in this column in the database

Numeric types

String type

Date and time type Numeric type

A NULL value

  • Understand as “no value” or “unknown value”
  • Do not use NULL for arithmetic operations; the result is still NULL

Data field attributes

UnSigned

  • unsigned
  • Declare that the data column does not allow negative numbers.

ZEROFILL

  • 0 filled
  • Less than digits are filled with 0, such as int(3), and 5 with 005

Auto_InCrement

  • Auto-growing, automatically increments the number of previous records by 1 for each entry (default)
  • It is usually used to set the primary key and is an integer
  • Start value and step size can be defined
    • Current table setting step (AUTO_INCREMENT=100) : Only the current table is affected
    • SET @@auto_increment_increment=5 ; Affect all tables that use increment (global)

NULL and NOT NULL

  • The default is NULL, that is, no value is inserted for the column
  • If set to NOT NULL, the column must have a value

DEFAULT

  • The default
  • Used to set default values
  • For example, the gender field, the default is “male”, otherwise “female”; If no value is specified for this column, the default value is the value of “male”
- the target: Varchar (20) Name, gender varchar(2), date of birth (datatime), home address,email -- before creating table, CREATE TABLE IF NOT EXISTS 'student' (' id 'int(4) NOT NULL AUTO_INCREMENT COMMENT' student ', 'name' varchar(30) NOT NULL DEFAULT 'anonymous' COMMENT ',' PWD 'varchar(20) NOT NULL DEFAULT '123456' COMMENT' password ', 'sex' varchar(2) NOT NULL DEFAULT 'male' COMMENT 'gender ',' birthday 'datetime DEFAULT NULL COMMENT' birthday ', 'address' varchar(100) DEFAULT NULL COMMENT 'address ',' email 'varchar(50) DEFAULT NULL COMMENT' email ', PRIMARY KEY (' id ') ENGINE=InnoDB DEFAULT CHARSET=utf8 SHOW CREATE DATABASE school; SHOW CREATE TABLE student; Table DESC student; SET sql_mode='STRICT_TRANS_TABLES';Copy the code

Type of data table

Sets the type of the data table

CREATE TABLE name (-- omit some code -- Mysql -- 1. # single line -- 2. */ multi-line comments)ENGINE = MyISAM (or InnoDB) -- SHOW ENGINES;Copy the code

MySQL datatype: MyISAM, InnoDB, HEAP, BOB, CSV…

Common MyISAM and InnoDB types:

Experience (applicable) :

  • MyISAM: save space and speed
  • For InnoDB: security, transaction processing and multi-user operation data tables

The storage location of the data table

  • MySQL tables are stored on disk as files
    • Includes table files, data files, and database options files
    • Location: Mysql installation directory \data\ where tables are stored. The directory name corresponds to the database name and the file name corresponds to the table name.
  • Note:
    • *.frm – Table structure definition file

    • *.myd — Data files

    • *.myi — Index file (index)

    • Innodb-type data tables have only one *. FRM file and ibdata1 file in the upper directory

    • Data tables of MyISAM type correspond to three files:

Set the data table character set

We can set different character sets for database, data table, data column.

  • When creating a TABLE, run the following command to set it: CREATE TABLE name ()CHARSET = utf8;
  • If no, set the parameters according to the MySQL database configuration file my.ini

Modifying a Database

ALTER TABLE ALTER TABLE

ALTER TABLE old TABLE name RENAME AS new TABLE name

ALTER TABLE table_name ALTER TABLE table_name

Modify field:

  • ALTER TABLE name ALTER TABLE name ALTER TABLE name
  • ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE

ALTER TABLE DROP field name

Delete table

Syntax: DROP TABLE [IF EXISTS] Specifies the name of the TABLE

  • IF EXISTS is optional to determine whether the data table EXISTS
  • An error is thrown if a table does not exist

other

1. Use backquotes (') as identifiers (library name, table name, field name, index, alias) to avoid the same name as the keyword! Chinese can also be used as an identifier! 2. Each library directory has an option file db.opt to save the current database. 3. Comment: single line comment # Comment content Multiple line comment /* Comment content */ Single line comment -- Comment content (standard SQL comment style, requiring double dashes followed by a space (space, TAB, newline, etc.)) 4. Pattern wildcard: _ Any single character % Any number of characters, including zero single quotes, need to be escaped \' 5. , "\G", "\G", only affects the display result. The rest of the place ends with a semicolon. Delimiter Modifies the statement terminator of the current conversation. SQL not sensitive to case (keyword) 7. Clear existing statement: \cCopy the code

MySQL03: DML language

A foreign key

Foreign key concepts

If a public key is the primary key in one relationship, that public key is called the foreign key of another relationship. Thus, a foreign key represents a correlation between two relationships. Tables with a foreign key of another relationship as the primary key are called primary tables, and tables with additional keys are called secondary tables of the primary table.

In practice, the association is represented by placing values from one table into a second table, using primary key values from the first table (including compound primary key values if necessary). At this point, the property in the second table that holds these values is called a foreign key.

Foreign key role

To maintain data consistency, integrity, the main purpose is to control the data stored in the foreign key table, constraint. To form an association between two tables, a foreign key can only reference the value of a column in the outer surface or use null values.

Create a foreign key

Specify foreign key constraints when creating a table

Create a foreign key CREATE TABLE 'grade' (' grade ID' INT(10) NOT NULL AUTO_INCREMENT COMMENT 'grade ID', 'gradename' VARCHAR(50) NOT NULL COMMENT 'grade ', PRIMARY KEY (' gradeID ') ENGINE=INNODB DEFAULT CHARSET= UTF8 -- CREATE TABLE (student id, name, gender, grade, phone, address, birth date, email, ID number 'student' (' studentno 'INT(4) NOT NULL COMMENT' studentNo ', 'studentName' VARCHAR(20) NOT NULL DEFAULT 'anonymous' COMMENT' studentNo ', 'sex' TINYINT(1) DEFAULT '1' COMMENT 'gender ',' gradeID 'INT(10) DEFAULT NULL COMMENT' grade ', 'phoneNum' VARCHAR(50) NOT NULL COMMENT 'phone ',' address 'VARCHAR(255) DEFAULT NULL COMMENT' address ', 'borndate' DATETIME DEFAULT NULL COMMENT 'iD ',' email 'VARCHAR(50) DEFAULT NULL COMMENT' id ', 'idCard' VARCHAR(18) DEFAULT NULL COMMENT 'iD ', PRIMARY KEY (' studentno'), KEY 'FK_gradeid' (' gradeID '), CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade` (`gradeid`) ) ENGINE=INNODB DEFAULT CHARSET=utf8Copy the code

Modify the table after it is built

Create a foreign key. ALTER TABLE 'student' ADD CONSTRAINT 'FK_gradeid' FOREIGN KEY (' gradeID ') REFERENCES 'grade' (`gradeid`);Copy the code

Remove the foreign key

Operation: Delete the grade table

Note: When deleting a table with a primary and foreign key relationship, delete the child table first and then the primary table

ALTER TABLE student DROP FOREIGN KEY FK_gradeid; ALTER TABLE student DROP INDEX FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeid FK_gradeidCopy the code

DML language

Database meaning: data storage, data management

Methods of managing database data:

  • Manage database data by SQLyog and other management tools
  • Manage database data through DML statements

DML: Data manipulation language

  • Used to manipulate data contained in a database object
  • Include:
    • INSERT (add data statement)
    • UPDATE (UPDATE data statement)
    • DELETE (DELETE data statement)

Add data

The INSERT command

Grammar:

INSERT INTO table name [(表 1, 表 2, 表 3,...)] VALUES(' 1',' 2',' 3')Copy the code

Note:

  • Use commas (,) to separate fields or values.
  • ‘Field 1, Field 2… ‘This section can be omitted, but the added values must correspond to the table structure, data column, order, and number.
  • Multiple data can be inserted at the same time. Separate values with commas (,).
How to add statements using statements? INSERT INTO table name [(表 1, 表 2, 表 3,...)] INSERT INTO grade(gradename) VALUES(' grade 1',' grade 2',' grade 3'); Primary key increment, can be omitted? INSERT INTO grade VALUES (' 四 '); INSERT INTO grade VALUE (' 四 ') INSERT INTO grade VALUE (' 四 ') Column count doesn't match VALUE count at row 1 INSERT INTO grade(gradename) VALUES (' senior '); INSERT INTO grade(gradename) VALUES (' senior ');Copy the code

Practice topic

Add data to the schedule subject yourself using the INSERT statement. Use the foreign key.

Modify the data

The update command

Grammar:

UPDATE table name SET column_name=value [,column_name2=value2,...  [WHEREcondition];Copy the code

Note:

  • Column_name is the data column to be changed
  • Value is the modified data, which can be a variable, specifically an expression or nested SELECT result
  • Condition is the filtering condition. If the condition is not specified, all columns in the table are modified

The WHERE condition clause

It can be simply interpreted as: conditionally filtering data from a table

Testing:

UPDATE grade SET gradename = 'grade' WHERE gradeID = 1;Copy the code

Delete the data

The DELETE command

Grammar:

DELETE FROM table name [WHERE condition];Copy the code

Note: condition is the filter condition. If condition is not specified, all column data in the table will be deleted

DELETE FROM grade WHERE gradeID = 5Copy the code

TRUNCATE command

Function: Used to completely empty the table data, but the table structure, index, constraint, etc.

Grammar:

TRUNCATE [TABLE] table_name; TRUNCATE Grade Clear the grade tableCopy the code

Note: Different from the DELETE command

  • Same: Data can be deleted without deleting table structures, but the TRUNCATE speed is faster
  • Different:
    • Use TRUNCATE TABLE to reset the AUTO_INCREMENT counter
    • Use of TRUNCATE TABLE does not affect transactions

Testing:

CREATE TABLE 'test' (' id 'INT(4) NOT NULL AUTO_INCREMENT,' coll 'VARCHAR(20) NOT NULL, PRIMARY KEY (' id ') ENGINE=INNODB DEFAULT CHARSET=utf8 VALUES('row1'),('row2'),('row3'); Delete FROM test; delete FROM test; Conclusion: If no Where value is specified, all columns in the TABLE are deleted, and logs are recorded. -- Conclusion: Truncate deletes data, and self-increasing the current value restores to the initial value and starts again; No logging is done. -- Use DELETE to clean up database table data from different engines as well. -- InnoDB: the increment column starts from the initial value (because it is stored in memory, it will be lost if power is off) -- MyISAM: The increment column still starts from the last increment data base (stored in a file, will not be lost)Copy the code

MySQL04: Use DQL to query data

DQL language

DQL(Data Query Language)

  • Query database data, such as a SELECT statement
  • Simple single-table queries or complex and nested queries with multiple tables
  • Database language is the most core, the most important statement
  • Use the most frequently used statement

SELECT the grammar

SELECT [ALL | DISTINCT] {* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,...]]} FROM table_name [as Table_alias] [left | right | inner join table_name2] - a federated query [WHERE]... [GROUP BY...] [HAVING] Specifies which fields to group results BY [ORDER BY...] - specifies the query record sorting by one or more conditions [LIMIT {[offset,] row_count | row_countOFFSET offset}]. -- Specifies from which records to which records to queryCopy the code

Note: the [] brackets represent optional, and the {} brackets represent required

Specify query fields

Select * from all columns in the table with **" \* "**; SELECT * FROM student; SELECT * FROM student; SELECT studentno,studentname FROM student;Copy the code

AS clause AS alias

Function:

  • A data column can be given a new alias
  • You can give the table a new alias
  • A calculated or summarized result may be replaced by another new name
SELECT studentno as student ID,studentname as name FROM student; SELECT studentno as student ID, studentName as name FROM student as s; SELECT CONCAT(' name :',studentname) as new name FROM student;Copy the code

Use of the DISTINCT keyword

SELECT * from SELECT columns where all columns are the same

SELECT * FROM result; SELECT studentno FROM result; SELECT DISTINCT studentno FROM result; DISTINCT removes duplicates (default: ALL)Copy the code

Columns that use expressions

Expressions in a database: Usually consist of text values, column values, NULL, functions, and operators

Application Scenarios:

  • The SELECT statement returns the result column

  • ORDER BY, HAVING, and so on in SELECT statements

  • Expressions are used in WHERE condition statements in DML statements

    SELECT @@auto_increment_increment; SELECT VERSION(); SELECT 100*3-1 AS AS; SELECT studentno,StudentResult+1 AS 'after' FROM result;Copy the code
  • Avoid disturbing development language programs with SQL returns containing ‘. ‘, ‘*’, and parentheses.

Where condition statement

Function: Used to retrieve records in a data table that match criteria

The search criteria can consist of one or more logical expressions, and the results are generally true or false.

Logical operator

test

-- Query that meets the conditions (WHERE) SELECT Studentno,StudentResult FROM result; SELECT Studentno,StudentResult FROM result WHERE StudentResult>=95 AND StudentResult<=100; SELECT Studentno,StudentResult FROM result WHERE StudentResult>=95 && StudentResult<=100; -- Fuzzy query (exact query) SELECT Studentno,StudentResult FROM result WHERE StudentResult BETWEEN 95 AND 100; Studentno,studentresult FROM result WHERE studentno! = 1000; -- Use NOT SELECT studentno,studentresult FROM result WHERE NOT studentno=1000;Copy the code

Fuzzy query: Comparison operator

Note:

  • Arithmetic operations can be performed between records of numeric data types;
  • Only data of the same data type can be compared;

Testing:

- fuzzy query between the and \ like \ \ in null - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = - like - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = -- query name is liu's classmate student number and name - like the combination of using wildcards: % (0 to any character) _ (one character) SELECT studentno,studentname FROM student WHERE studentname LIKE 'liu %'; Studentno,studentname FROM student WHERE studentname LIKE 'student_ '; SELECT studentname FROM student WHERE studentname LIKE' student_ '; Studentno,studentname FROM student WHERE studentname LIKE 'student__ '; studentno,studentname FROM student WHERE studentname LIKE' student__ '; SELECT studentno,studentname FROM student WHERE studentname LIKE '% student% '; -- Use escape symbol '\' -- use custom escape keyword: ESCAPE ':' -- ============================================= -- IN -- ============================================= -- SELECT studentno,studentname FROM student WHERE studentno IN (1000,1001,1002); - query address IN Beijing, nanjing, luoyang, henan students SELECT studentno, studentname, address the FROM student WHERE the address IN (' Beijing ', 'nanjing', 'henan luoyang); - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = - NULL empty - = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = - Studentname =NULL SELECT studentname FROM student WHERE BornDate is NULL; SELECT studentname FROM student WHERE BornDate IS NOT NULL; SELECT studentname FROM student WHERE Address= "OR Address IS null;Copy the code

Join queries

The JOIN contrast

Seven Join:

test

Select * from outer join left JOIN; select * from outer join; select * from outer join; select * from outer join; select * from outer join; select * from outer join Join right outer join right outer join right outer join right outer join right outer join right outer join right outer join right outer join right outer join right outer join right outer join */ SELECT * FROM student; SELECT * FROM student; SELECT * FROM student; SELECT * FROM result; Select * from student result; select * from student result; select * from student result; (connection) * / SELECT s.s tudentno, studentname, subjectno, StudentResult FROM student s INNER JOIN result ON r.s tudentno = r Also can realize s.s tudentno - RIGHT connection () the SELECT s.s tudentno, studentname, subjectno, StudentResult FROM student "s RIGHT JOIN result ON r R.s tudentno = s.s tudentno - equivalent to connect the SELECT s.s tudentno, studentname, subjectno, StudentResult FROM student s, Result r WHERE r.tudentno = s.tudentno SELECT result R WHERE r.tudentno = s.tudentno s.studentno,studentname,subjectno,StudentResult FROM student s LEFT JOIN result r ON r.studentno = s.studentno -- Check the lack of test students (LEFT connection application scenario) SELECT s.s tudentno, studentname, subjectno, StudentResult FROM student s LEFT the JOIN result ON r R.tudentno = s.tudentno WHERE StudentResult IS NULL SELECT student id, student name, subject name, score from StudentResult s.studentno,studentname,subjectname,StudentResult FROM student s INNER JOIN result r ON r.studentno = s.studentno INNER JOIN `subject` sub ON sub.subjectno = r.subjectnoCopy the code

Since the connection

/* Select * from a table that contains column ID, */ -- CREATE a TABLE CREATE TABLE 'category' (' categoryID 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主 体 iD ', 'PID' INT(10) NOT NULL COMMENT '主 体 iD ', 'categoryName' VARCHAR(50) NOT NULL COMMENT 'catid ', PRIMARY KEY (' categoryID ') ENGINE=INNODB AUTO_INCREMENT=9 DEFAULT CHARSET= UTf8 -- INSERT INTO 'category (` categoryid `, ` pid ` ` categoryName `) VALUES (' 2 ', '1', 'information technology), (' 3', '1', 'software development), (' 4', '3', 'database'), (' 5 ', '1', 'art design), (' 6 ', '3', 'web development), (' 7', '5', 'ps technology), (' 8', '2', 'office information'); SELECT * from testoryName AS SELECT * from testoryname AS SELECT * from testoryname AS SELECT * from testoryname AS SELECT * from testoryname 'categoryID' = 'catid' FROM category AS a,category AS B WHERE a. 'categoryID' = B. 'pid' -- Consider: query took part in the examination of students information (student id, student's name, course name, score) SELECT s.s tudentno, studentname, subjectname, StudentResult FROM student s INNER JOIN Result r ON r.tudentno = s.tudentno INNER JOIN 'subject' sub ON sub.subjectno = r.subjectno SELECT studentno AS student ID, studentName AS studentname,gradename AS gradename FROM student s INNER JOIN grade g ON S. 'GradeId' = G. 'GradeID' SELECT SubjectName AS SUBJECT name,gradename AS grade FROM SUBJECT sub INNER JOIN grade G ON Sub. Gradeid = g.g radeid, query the database structure - 1 all the exam results (student id student's name Course name Grades) SELECT s.s tudentno, studentname, subjectname, StudentResult  FROM student s INNER JOIN result r ON r.studentno = s.studentno INNER JOIN `subject` sub ON r.subjectno = sub.subjectno WHERE SubjectName =' database structure-1 'Copy the code

Sorting and paging

test

/ * = = = = = = = = = = = = = = sort = = = = = = = = = = = = = = = = syntax: the ORDER BY the ORDER BY statement is used to according to the specified column to sort the result set. BY default, the ORDER BY statement sorts records in ASC ascending ORDER. If you want to sort the records in descending order, use the DESC keyword. 1 * /, query the database structure all the exam results (student id student's name Course name Grades) - according to the result descending order SELECT s.s tudentno, studentname, subjectname, StudentResult the FROM student s INNER JOIN result r ON r.studentno = s.studentno INNER JOIN `subject` sub ON r.subjectno = sub.subjectno WHERE Subjectname = 'database structure - 1' ORDER BY StudentResult DESC / * = = = = = = = = = = = = = = paging = = = = = = = = = = = = = = = = syntax: SELECT * FROM table LIMIT/offset, rows | rows offset offset benefits: (user experience, network transmission, query pressure) is derived: the first page: LIMIT 0, 5 second page: Limit 5,5 page 3: limit 10,5...... N page: Limit (pageno-1)*pageSzie,pageSzie [pageNo: page number,pageSize: number of pages displayed on a page] */ -- Display 5 data on a page SELECT s.studentno,studentname,subjectname,StudentResult FROM student s INNER JOIN result r ON r.studentno = s.studentno INNER JOIN 'subject' sub ON R.subjectNo = sub. subjectNo WHERE SubjectName =' database structure-1 'ORDER BY StudentResult DESC, Studentno LIMIT 0,5 -- SELECT top 10 students from JAVA studentno LIMIT 0,5 -- SELECT top 10 students from JAVA studentno LIMIT 0,5 -- SELECT top 10 students from JAVA studentno LIMIT 0,5 -- SELECT top 10 students from JAVA studentno LIMIT 0,5 -- SELECT top 10 students from JAVA studentno LIMIT 0,5 s.studentno,studentname,subjectname,StudentResult FROM student s INNER JOIN result r ON r.studentno = s.studentno INNER JOIN 'subject' sub ON r.subjectno = sub.subjectno WHERE subjectname='JAVA first year 'ORDER BY StudentResult DESC LIMIT 0,10Copy the code

The subquery

/*============== ================ what is a subquery? Nested query can be composed of multiple sub-queries, the solution is from the inside and outside; Subqueries generally return collections, so the IN keyword is recommended. * /, query the database structure - 1 all the exam results (student id, course number, grade), and grade descending order - method one: use the connection query SELECT studentno, r.s ubjectno, StudentResult FROM the result of r INNER JOIN 'subject' sub ON R. 'SubjectNo' =sub. 'SubjectNo' WHERE SubjectName = 'database structure-1' ORDER BY studentResult DESC; - method 2: use a subquery (execution sequence: FROM inside and outside), the SELECT studentno subjectno, StudentResult FROM the result the WHERE subjectno = (SELECT subjectno the FROM 'subject' WHERE SubjectName = 'subjectName -1') ORDER BY studentResult DESC; SELECT id,studentname FROM student s INNER JOIN result r ON SELECT id,studentname FROM student s INNER JOIN result r ON S. 'StudentNo' = r. 'StudentNo' INNER JOIN 'subject' sub ON sub. 'SubjectNo' = R. 'SubjectNo' WHERE SubjectName = 'Advanced Mathematics -2' AND StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 -- StudentResult>=80 'StudentNo' =r. 'StudentNo' WHERE StudentResult>=80 r.studentno,studentname FROM student s INNER JOIN result r ON s.`StudentNo`=r.`StudentNo` WHERE StudentResult>=80 AND Subjectno =(SELECT SubjectNo FROM 'subject' WHERE SubjectName = 'Advanced-mathematics -2' studentno,studentname FROM student WHERE studentno IN( SELECT studentno FROM result WHERE StudentResult>=80 AND Subjectno =(SELECT SubjectNo FROM 'subject' WHERE SubjectName = 'advanced Mathematics -2')) Query the top 5 students' grade information (student id, name, score) of C-language -1. Use sub-query to query the name of guo Jing's grade */Copy the code

MySQL05: MySQL function

Commonly used functions

Data function

SELECT ABS(-8); /* absolute value */ SELECT CEILING(9.4); /* SELECT FLOOR(9.4); /* SELECT RAND(); SELECT SIGN(0); SELECT SIGN(0); /* Symbol functions: negative numbers return -1, positive numbers return 1,0 returns 0*/Copy the code

String function

SELECT CHAR_LENGTH(' persistence will succeed '); /* Return the number of characters contained in the string */ SELECT CONCAT(' I ',' love ',' program '); */ SELECT INSERT(' I love programming helloworld',1,2,' super love '); */ SELECT LOWER('KuangShen'); /* SELECT UPPER('KuangShen'); /* SELECT LEFT('hello,world',5); /* SELECT RIGHT('hello,world',5); /* cut from the right */ SELECT REPLACE(' crazy god says persist will succeed ',' persist ',' try hard '); /* replace string */ SELECT SUBSTR(' persist, succeed ',4,6); /* SELECT REVERSE(' stick to it '); SELECT REPLACE(studentname,' studentname ',' studentname ') AS new name FROM student WHERE studentname LIKE '%';Copy the code

Date and time functions

SELECT CURRENT_DATE(); /* SELECT CURDATE(); /* SELECT NOW(); /* get the current date and time */ SELECT LOCALTIME(); /* SELECT SYSDATE(); SELECT YEAR(NOW()) from (SELECT * from (NOW())); SELECT MONTH(NOW()); SELECT DAY(NOW()); SELECT HOUR(NOW()); SELECT MINUTE(NOW()); SELECT SECOND(NOW());Copy the code

System information function

SELECT VERSION(); /* version */ SELECT USER(); / * * / usersCopy the code

Aggregation function

The name of the function describe
COUNT() Return the total number of records that meet the Select condition, such as Select count(*)
SUM() Returns a numeric field or expression column for statistics, and returns the sum of a column.
AVG() Usually for numerical fields or expression columns, returns the average value of a column
MAX() You can perform statistics for numeric fields, character fields, or expression columns, returning the maximum value.
MIN() You can perform statistics for numeric fields, character fields, or expression columns, returning the smallest value.
-- aggregate function /*COUNT: non-empty */ SELECT COUNT(studentname) FROM student; SELECT COUNT(*) FROM student; SELECT COUNT(1) FROM student; /* recommend */ -- by definition, count(1) and count(*) represent queries on all rows. -- count(field) counts the number of occurrences of the field in the table, ignoring the case that the field is null. That is, records whose field is null are not counted. -- count(*) includes all columns, equal to the number of rows, including null columns when counting results; -- count(1) uses 1 to represent the line of code, and contains records with null fields when counting results. /* Many people think that count(1) is more efficient than count(*) because count(*) has a full table scan and count(1) can be queried against a single field. In fact, both count(1) and count(*) scan the entire table, counting all records, including those that are null, so their efficiency is almost the same. The count(field), on the other hand, counts the number of records for which the field is not null. Here are some comparisons: 1) Count (1) is faster than count(*) when there is no primary key; 2) Count (primary key) is most efficient when there is a primary key; 3) If the table has only one field, count(*) is efficient. */ SELECT SUM(StudentResult) AS SUM FROM result; SELECT AVG(StudentResult) AS average score FROM result; SELECT MAX(StudentResult) AS the highest score FROM result; SELECT MIN(StudentResult) AS the lowest score FROM result;Copy the code

Topic:

Query the average, highest, and lowest scores of different courses. Prerequisite: SELECT SubjectName,AVG(StudentResult) AS, and MAX(studentResult) AS Maximum score,MIN(StudentResult) AS minimum score FROM result AS r INNER JOIN 'subject' AS s ON R.subjectno = s.subjectno GROUP BY R.subjectno HAVING average score >80; /* where group by. Filters placed after groups use HAVING.. Because having is filtered from the previously filtered field, where is filtered directly from the > field in the data table */Copy the code

MD5 encryption

I. Introduction to MD5

MD5 is message-digest Algorithm 5 to ensure the consistency of information transmission. It is one of the hashing algorithms widely used in computers. MD5 has been widely implemented in mainstream programming languages. Computing data (such as Chinese characters) into another fixed length value is the basis of the hashing algorithm. The predecessors of MD5 are MD2, MD3 and MD4.

Second, to achieve data encryption

Create a new table, testMD5

 CREATE TABLE `testmd5` (
  `id` INT(4) NOT NULL,
  `name` VARCHAR(20) NOT NULL,
  `pwd` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`)
 ) ENGINE=INNODB DEFAULT CHARSET=utf8
Copy the code

Insert some data

 INSERT INTO testmd5 VALUES(1,'kuangshen','123456'),(2,'qinjiang','456789')
Copy the code

If we want to encrypt the PWD column, the syntax is:

 update testmd5 set pwd = md5(pwd);
Copy the code

If the password of a user (such as Kuangshen) is encrypted separately:

 INSERT INTO testmd5 VALUES(3,'kuangshen2','123456')
 update testmd5 set pwd = md5(pwd) where name = 'kuangshen2';
Copy the code

Insert new data automatically encrypted

 INSERT INTO testmd5 VALUES(4,'kuangshen3',md5('123456'));
Copy the code

Query the login user information (md5 comparison is used to check the encrypted password entered by the user for comparison)

 SELECT * FROM testmd5 WHERE `name`='kuangshen' AND pwd=MD5('123456');
Copy the code

summary

- = = = = = = = = = = = = = = = = built-in function = = = = = = = = = = = = = = = = - numerical function abs (x) - absolute value abs (10.9) = 10 format (x, D) -- format the thousandth value format(1234567.456, Ceil (10.1) = 11 floor(x) -- floor(10.1) = 10 round(x) -- round mod(m, SQRT (x) -- arithmetic square root rand() -- random number truncate(x, D) -- truncate d decimal -- date function now(), current_timestamp(); -- The current date, time current_date(); -- Current date current_time(); -- Current time date(' YYYY-MM-DD hh:ii:ss'); Time (' YYYY-MM-DD hh:ii:ss'); - to get part time date_format (' ii yyyy - - dd hh: mm: ss ', '% d % % % d % m % b y % j'); -- Format time unix_timestamp(); -- Get the Unix timestamp from_unixtime(); String function length(string) -- String length, Bytes char_length(string) -- The number of characters in string substring(STR, Position [,length]) -- replace(STR,search_str,replace_str) -- replace search_str with replace_str in STR Instr (string, subString) -- Returns the first occurrence of subString in string concat(string [,...] Charset (STR) -- return string character set lcase(string) -- convert to lowercase left(string, Load_file (file_name) - load_file(file_name) - locate(substring, String [,start_position]) -- same as instr, but can specify start position lpad(string, length, Ltrim (string) -- remove the front space -- repeat(string, count) -- repeat count times rpad(string, length, Pad) -- add pad after STR until length is length rtrim(string) -- remove back space STRCMP (string1,string2) -- compare two string sizes character by character -- aggregate function count() sum(); max(); min(); avg(); Group_concat () -- other common functions md5(); default();Copy the code

MySQL06: Transactions and indexes

The transaction

What is a transaction

  • A transaction is a group of SQL statements executed in the same batch
  • If an SQL statement fails, all SQL in that batch is canceled
  • MySQL transactions only support InnoDB and BDB table types

The ACID principle of transactions

Atomicity (Atomic)

  • All operations in the whole transaction are either completed or not completed, and cannot be stopped in some intermediate link. If a transaction fails during execution, it will be rolled back to the state before the transaction began, as if the transaction had never been executed.

Consistency (Consist of)

  • A transaction can encapsulate state changes (unless it is read-only). Transactions must always keep the system in a consistent state, no matter how many concurrent transactions there are at any given time. That is: if the transaction is concurrent, the system must operate as if it were a serial transaction. For example, if there are five accounts and each account has a balance of 100 yuan, then the total amount of the five accounts is 500 yuan. If multiple transfers occur between these five accounts simultaneously, no matter how many concurrently, For example, transfer 5 yuan between accounts A and B, 10 yuan between accounts C and D, 15 yuan between accounts B and E, the total amount of the five accounts should still be 500 yuan, which is protective and invariable.

Isolation (Isolated)

  • Isolated states execute transactions as if they were the only operations performed by the system at a given time. If you have two transactions, running at the same time and performing the same function, the isolation of the transaction ensures that each transaction is considered by the system to be the only one using the system. This property is sometimes called serialization, and to prevent confusion between transaction operations, requests must be serialized or serialized so that only one request is used for the same data at a time.

Durability (Durable)

  • After the transaction completes, changes made to the database by the transaction are persisted in the database and are not rolled back.

The basic grammar

Set autocommit = 0; /* close */ SET autocommit = 1; /* enable */ -- notice: -- 1.MySQL default is automatic commit -- 2. START TRANSACTION -- COMMIT a TRANSACTION to the database -- ROLLBACK the TRANSACTION to its original state SET autocommit =1; ROLLBACK TO SAVEPOINT ROLLBACK TO SAVEPOINT RELEASE SAVEPOINT delete SAVEPOINTCopy the code

test

/* Question A: Buy A commodity with A price of 500 yuan online, and transfer the money online. CREATE DATABASE 'shop' CHARACTER SET utf8 */ CREATE DATABASE 'shop' CHARACTER SET utf8 COLLATE utf8_general_ci; USE `shop`; CREATE TABLE `account` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(32) NOT NULL, ` cash ` DECIMAL (9, 2) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 INSERT INTO account (`name`,`cash`) VALUES('A',2000.00),('B',10000.00) -- SET autocommit = 0; -- Disable automatic commit START TRANSACTION; UPDATE account SET cash=cash-500 WHERE 'name' ='A'; UPDATE account SET cash=cash+500 WHERE `name`='B'; COMMIT; -- Commit transaction # rollback; SET autocommit = 1; -- Restore automatic submissionCopy the code

The index

The role of indexes

  • Improve query speed
  • Ensure that data is unique
  • You can speed up the join between tables to achieve referential integrity between tables
  • When using grouping and sorting clauses for data retrieval, grouping and sorting time can be significantly reduced
  • Full text search field for search optimization.

classification

  • Primary Key index
  • Unique index
  • General Index
  • FullText index

The primary key index

Primary key: an attribute group that uniquely identifies a record

Features:

  • The most common type of index
  • Ensure that data records are unique
  • Determines where specific data is recorded in the database

The only index

Purpose: Avoid duplicate values in a data column of the same table

Differences from primary key indexes

  • There can be only one primary key index
  • There may be multiple unique indexes
CREATE TABLE `Grade`( `GradeID` INT(11) AUTO_INCREMENT PRIMARYKEY, 'GradeName' VARCHAR(32) NOT NULL UNIQUE -- or UNIQUE KEY 'GradeID')Copy the code

Conventional index

Function: Quickly locate specific data

Note:

  • The index and key keywords can both set regular indexes
  • The field that should be added to the query search criteria
  • Do not add too many regular indexes to interfere with data insertion, deletion, and modification operations
CREATE TABLE 'result' (-- omit some code INDEX/KEY 'ind' (' studentNo ', 'subjectNo') -- ADD ALTER TABLE 'result' ADD after creation  INDEX `ind`(`studentNo`,`subjectNo`);Copy the code

The full text indexing

Baidu search: full text index

Function: Quickly locate specific data

Note:

  • Can only be used for data tables of type MyISAM
  • Can only be used with CHAR, VARCHAR, TEXT data column types
  • Suitable for large data sets
/* # CREATE TABLE name (1); , field name 2 Data type [integrity constraints...] [UNIQUE | FULLTEXT | SPATIAL] INDEX | KEY INDEX of [name] (field name [(length)] [ASC | DESC])); Method # 2: the CREATE INDEX creation ON the existing table CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX INDEX name ON the name of the table (field name [(length)] [ASC | DESC]); Method # 3: the ALTER TABLE in an existing TABLE create indexes on the ALTER TABLE tablename ADD [UNIQUE | FULLTEXT | SPATIAL] INDEX INDEX name (field name [(length)] [ASC | DESC]); DROP INDEX ON table name; ALTER TABLE table_name DROP PRIMARY KEY; # SHOW INDEX FROM student; ALTER TABLE 'school'. 'student' ADD FULLTEXT INDEX 'studentname' (' studentname '); /*EXPLAIN SELECT * FROM student WHERE studentno='1000'; /* Use full-text index */ -- full-text search is done with the MATCH() function. The search string is given as an argument to against(). The search is performed regardless of alphabetic case. For each row in the table, MATCH() returns a correlation value. That is, the similarity scale between the search string and the text that records the columns specified in the MATCH() list. EXPLAIN SELECT *FROM student WHERE MATCH(studentname) AGAINST('love'); MySQL 5.6, only MyISAM storage engine supports full-text indexing; MySQL 5.6, only MyISAM storage engine supports full-text indexing. MySQL 5.6 and later, MyISAM and InnoDB storage engines support full-text indexing; Full-text indexes can be created only for fields whose data types are CHAR, VARCHar, text, and their families. When testing or using full-text indexes, check to see if your version of MySQL, storage engine, and data type support full-text indexes. * /Copy the code

Extension: Test index

Build app_user table:

CREATE TABLE `app_user` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 'name' varchar(50) DEFAULT 'COMMENT ',' email 'varchar(50) NOT NULL COMMENT' username ', 'phone' varchar(20) DEFAULT 'COMMENT' mobile phone number ', 'gender' tinyint(4) unsigned DEFAULT '0' COMMENT 'Gender (0: male; 1: Varchar (100) NOT NULL COMMENT 'password ',' age 'tinyint(4) DEFAULT '0' COMMENT' age ', `create_time` datetime DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATECURRENT_TIMESTAMP, PRIMARY KEY (' id ') ENGINE=InnoDB DEFAULT CHARSET= utf8MB4 COMMENT='app 'Copy the code

Batch insert data: 100w

DROP FUNCTION IF EXISTS mock_data; DELIMITER $$ CREATE FUNCTION mock_data() RETURNS INT BEGIN DECLARE num INT DEFAULT 1000000; DECLARE i INT DEFAULT 0; WHILE I < num DO INSERT INTO app_user(' name ', 'email ',' phone ', 'gender ',' password ', 'age') VALUES(CONCAT(' user ', I), '[email protected]', CONCAT('18', FLOOR(RAND()*(999999999-100000000)+100000000)),FLOOR(RAND()*2),UUID(), FLOOR(RAND()*100)); SET i = i + 1; END WHILE; RETURN i; END; SELECT mock_data();Copy the code

Index efficiency test

There is no index

SELECT * FROM app_user WHERE name = '9999'; SELECT * FROM app_user WHERE name = '9999'; SELECT * FROM app_user WHERE name = '9999'; Mysql > EXPLAIN the SELECT * FROM app_user WHERE name = '9999' \ G * * * * * * * * * * * * * * * * * * * * * * * * * * * 1. Row *************************** id: 1 select_type: SIMPLE table: app_user partitions: NULL type: ALL possible_keys: NULL Key: NULL KEY_len: NULL ref: NULL rows: 992759 filtered: 10.00 Extra: Using WHERE 1 row in set, 1 warning (0.00 SEC)Copy the code

Create indexes

CREATE INDEX idx_app_user_name ON app_user(name);
Copy the code

Testing plain indexes

Mysql > EXPLAIN the SELECT * FROM app_user WHERE name = '9999' \ G * * * * * * * * * * * * * * * * * * * * * * * * * * * 1. Row *************************** id: 1 select_type: SIMPLE table: app_user partitions: NULL type: ref possible_keys: Idx_app_user_name Key: idx_app_user_name KEY_len: 203 ref: const rows: 1 filtered: 100.00 Extra: NULL 1 row in set, 1 warning (0.00 SEC) mysql> SELECT * FROM app_user WHERE name = 'user 9999'; 1 row in set (0.00 SEC) mysql> SELECT * FROM app_user WHERE name = '9999'; 1 row in set (0.00 SEC) mysql> SELECT * FROM app_user WHERE name = '9999'; 1 row in set (0.00 SEC)Copy the code

The index criterion

  • More indexes are not always better
  • Do not index data that changes frequently
  • Do not add indexes to tables with small data volumes
  • The index should generally be added to the field in the search condition

The data structure of the index

Hash index (btree); hash index (btree); hash index (btree) Innodb supports transactions, row-level locking, b-tree, full-text, and other indexes, but does not support Hash indexes. MyISAM does not support transactions, table-level locking, b-tree, full-text and other indexes, but does not support Hash indexes. Memory does not support transactions, table-level locking, b-tree and Hash indexes, and full-text indexes. NDB supports transactions, row-level locking, and Hash indexes, but does not support b-tree and full-text indexes. Archive does not support transactions, table-level locking, and indexes such as B-tree, Hash, and full-text.Copy the code

MySQL07: Permissions and how to design a database

User management

Create a user using SQLyog and grant permissions for the demo

Basic commands

/* User and permission management */ ------------------ user information table: Mysql. User -- Refresh PRIVILEGES FLUSH PRIVILEGES -- Add user CREATE user kuangshen IDENTIFIED BY '123456' CREATE user user IDENTIFIED BY [PASSWORD] PASSWORD (string) - You must have global CREATE USER permission for the mysql database, or you must have INSERT permission. - Users can be created but cannot be assigned rights. For example, 'user_name'@'192.168.1.1' - The PASSWORD must be quoted as well as the PASSWORD for pure digits. - To specify a PASSWORD in plain text, ignore the PASSWORD keyword. To specify the PASSWORD as the mixed value returned by the PASSWORD() function, PASSWORD -- RENAME USER kuangshen TO kuangshen2 RENAME USER old_user TO new_user -- SET the PASSWORD SET PASSWORD = PASSWORD(' PASSWORD ') -- SET PASSWORD FOR USER = PASSWORD(' PASSWORD ') -- SET PASSWORD FOR USER -- DROP USER kuangshen2 DROP USER GRANT privileges ON table name TO user name [IDENTIFIED BY [PASSWORD] 'PASSWORD '] - all PRIVILEGES - *.* All tables in all libraries - The library name. Select * from root@localhost; select * from root@localhost; SHOW GRANTS FOR user name -- Check current user privileges SHOW GRANTS; Or SHOW GRANTS FOR CURRENT_USER; Or SHOW GRANTS FOR CURRENT_USER(); REVOKE ALL PRIVILEGES, GRANT OPTION FROM user nameCopy the code

Permissions to explain

-- ALL [PRIVILEGES] -- Set ALL simple PRIVILEGES except GRANT OPTION ALTER -- Allow the use of ALTER TABLE ALTER ROUTINE -- change or cancel the stored subroutine CREATE -- CREATE TABLE CREATE ROUTINE -- CREATE a stored subroutine CREATE TEMPORARY TABLES -- CREATE TEMPORARY TABLE CREATE USER -- CREATE USER, DROP USER, RENAME USER, and REVOKE ALL PRIVILEGES are allowed. CREATE VIEW -- Allow CREATE VIEW DELETE -- allow DELETE DROP -- allow DROP TABLE EXECUTE -- allow the user to run the stored subroutine FILE -- Allow SELECT... INTO OUTFILE and LOAD DATA INFILE INDEX -- CREATE INDEX and DROP INDEX INSERT -- INSERT LOCK TABLES -- Allow LOCK TABLES PROCESS for TABLES where you have SELECT privileges -- allow SHOW FULL PROCESSLIST REFERENCES -- not RELOAD -- Allow FLUSH REPLICATION REPLICATION SLAVE -- Used for REPLICATION SLAVE servers (read binary log events from the master server) SELECT -- use SELECT SHOW DATABASES -- SHOW VIEW -- allow SHOW CREATE VIEW SHUTDOWN -- allow mysqladmin SHUTDOWN SUPER -- allow CHANGE MASTER, KILL, PURGE MASTER LOGS and SET GLOBAL statements, mysqladmin debug Allows you to connect (once), even if max_connections has been reached. UPDATE - allows you to use the UPDATE USAGE, synonymous with the term "without permission GRANT OPTION - allowed to GRANT permission table maintenance / * * /, analysis and storage table keyword distribution ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE TABLE name... CHECK TABLE tbl_name [, tbl_name]... [option] ... Option = {QUICK | FAST | MEDIUM | EXTENDED | CHANGED} - process data file fragments of OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...Copy the code

MySQL backup

Database Backup Necessity

  • Ensure that important data is not lost
  • Data transfer

MySQL database backup method

  • Mysqldump backup tool
  • Database management tools, such as SQLyog
  • Copy database files and related configuration files directly

The mysqldump client

Function:

  • Dump database
  • Collect database for backup
  • Move the data to another SQL server, not necessarily a MySQL server

Mysqldump -uroot -p123456 school student >D:/a.sql mysqldump -u username -p password table name >D:/a.sql 2. Mysql > mysqldump -uroot -p123456 school student result >D:/a.sql mysqldump -u username -p password mysqldump table 1 table 2 Table 3  -- mysqldump -uroot -p123456 school >D:/a.sql mysqldump -u -p mysqldump >D:/a.sql 4. Dump -uroot -p123456 -b school >D:/a.sql mysqldump -u username -p password -b database name >D:/a.sql D:/a.sql source backup file 2. Mysql -u user name -p password database name < backup file if no login is requiredCopy the code

Standardized database design

Why database design

When the database is more complex, we need to design the database

Bad database design:

  • Data redundancy and storage space waste
  • Data update and insert exceptions
  • Poor program performance

Good database design:

  • Saves data storage space
  • Ensure data integrity
  • Facilitate the development of database application system

Database design in software project development cycle:

  • Requirements analysis stage: analyze customer’s business and data processing needs
  • Summary design stage: design the e-R model diagram of the database and confirm the correctness and completeness of the demand information.

Steps for designing a database

  • To collect information
    • Communicate and talk with the system personnel, fully understand the user needs, understand the database needs to complete the task.
  • Identify an Entity
    • Identifies the key object or entity to be managed by the database. Entities are generally nouns
  • Identify the details that each entity needs to store [Attribute]
  • Identify the Relationship between entities.

The three major paradigm

Question: Why is data normalization needed?

Substandard table design can cause problems:

  • Duplicate information
  • Update anomalies
  • Insert the abnormal
    • Information cannot be represented correctly
  • Remove abnormal
    • Loss of valid information

The three major paradigm

First Normal Form (1st NF)

The goal of the first normal form is to ensure the atomicity of each column, satisfying the first normal form if each column is the smallest non-separable unit of data

Second Normal Form (2nd NF)

The second normal form (2NF) is established on the basis of the first normal form (1NF), that is to satisfy the second normal form (2NF) must first satisfy the first normal form (1NF).

The second normal form requires that each table describe only one thing

Third Normal Form (3rd NF)

A relationship satisfies the third normal form if it satisfies the second normal form and all columns except the primary key do not pass dependent on the primary key column.

The third normal form requires that each column in the data table is directly related to the primary key, not indirectly.

The relationship between normalization and performance

To meet certain business goals, database performance is more important than canonical databases

At the same time of data normalization, the performance of database should be considered comprehensively

Significantly reduce the time needed to search for information from a given table by adding additional fields

E [tbl_name]… [option]… Option = {QUICK | FAST | MEDIUM | EXTENDED | CHANGED} – sorting data file fragments of OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [tbl_name]…

MySQL > replace database with SQLyog; MySQL > replace database with SQLyog; MySQL > replace database with SQLyog * * * * mysqldump client: - database dump - collection database backups - transfers the data to another SQL server, is not necessarily the MySQL server [outside chain archived in images... (img - kwwnyH4I - 1604630594823)"Copy the code

Export —

  1. Mysqldump -uroot -p123456 school student >D:/a.sql mysqldump -u -p mysqldump -d :/a.sql
  2. Mysqldump -uroot -p123456 school student result >D:/a.sql mysqldump -u username -p password
  3. Mysql > mysqldump -uroot -p123456 school >D:/a.sql mysqldump -u -p mysql >D:/a.sql
  4. Mysqldump -uroot -p123456 -b school >D:/a.sql mysqldump -u username -p password -b database name > filename (D:/a.sql)

-w can carry backup conditions

– import

  1. — source D:/a.sql source Backup file
  2. Mysql -u user name -p password database name < backup file if no login is required
** ** Poor database design :** - Data redundancy, storage space waste - data update and insert exceptions - poor program performance ** Good database design :** - Save data storage space - to ensure data integrity - facilitate the development of database application system ** Database design in the development cycle of software projects :** - Requirements analysis stage: Analyze customers' business and data processing needs - Outline design stage: design e-R model diagram of the database, confirm the correctness and integrity of demand information. - Identify the key objects or entities to be managed by the database. An Entity is usually a noun. - Identify the details that each Entity needs to store Three paradigms ** Question: Why data normalization? ** Non-standard table design can cause problems: - Information duplication - update exception - Insertion exception - Incorrect representation of information - Deletion exception - loss of valid information > The Three paradigms ** First Paradigms (1st NF)** The goal of first paradigms is to ensure atomicity of each column, satisfying first paradigms if each column is the smallest non-divisible unit of data The second normal form (2NF) is based on the first normal form (1NF), that is, to satisfy the second normal form (2NF), one must first satisfy the first normal form (1NF). The second normal form requires that each table describe only one thing ** Third normal Form ** A relationship is third normal form if it satisfies the second normal form and all columns except the primary key do not pass dependent on the primary key column. The third normal form requires that each column in the data table is directly related to the primary key, not indirectly. The relationship between standardization and performance of * * * * to meet some business objectives, database performance is more important than the standardized database at the same time as the data standardization, to comprehensively consider the performance of the database By adding additional fields in a given table, to reduce the need to search information from a lot of the time required by inserting computed columns in a given table, to facilitate the queryCopy the code