Mysql database learning and summary

Preface

   I am a test engineer. For data analysts, development engineers, and test engineers, database operation is the most basic and important technology. This article is a summary of Mysql database during my study and work.


1. Basic concepts

1. Database: It is a collection of organized, shared and unified management related data stored in a computer, composed of tables, relationships, and operation objects.
2. The characteristics of transactions: atomicity, consistency, isolation, and durability.
3. Database management system: is a large-scale software that manipulates and manages databases, used to create, use, and maintain databases. DDL: Data Definition Language, DML: Data Manipulation Language, DCL: Data Control Language.
4. Mysql database features: high performance, cross-platform, support for multiple users, free and open source, simple to use.
5. Primary key: It is the only field with no specific business meaning that can identify a record in a table, such as identity photo, card number, mobile phone number, email, etc. can all be used as primary keys. Features: a. The fields of the primary key are unique; b. The fields of the primary key cannot be empty; c. The primary key has its own index; d. Multiple fields can form the primary key; e. A table has only one primary key.
6, foreign key: used to establish a relationship between two tables, need to specify which column to refer to the main table. If the primary key of table A is a field in table B, the field is called a foreign key of table B, table A (primary table), table B (slave table). Foreign keys are used to achieve referential integrity. When the master table is updated, the slave table is also updated. When the master table is deleted, if the slave table has a matching item, the deletion fails.
7. Index: It is a single, physical storage structure that sorts the values ​​of one or more columns in a database table. Advantages: using indexes can speed up data query speed, disadvantages: indexes will take up memory and disk space, and will increase the maintenance cost of the database management system.
8. View:A virtual table does not store any data. The data of the view comes from the base table when the view is created. Function: Simplify operation, simplify complex SQL, B. Avoid data redundancy, C. Improve data security, D. Improve data logic independence.


Two, Mysql data type

Mysql data type: date type: date /time /datetime/timestamp, string type: char/varchar/text, floating point type: decimal/float/double, integer type: tinyint/smallint/mediumint/int/bigint.

In Mysql, except string types need to set the length, other types have default lengths.

 


3. Data control language DCL

1. System operation

Check the port according to the process name: 1.tasklist|findstr mysql 2.netstat -ano|findstr pid
Check the process according to the port: 1.netstat -ano|findstr port 2.tasklist |findstr pid
start mysql service: net start mysql
stop mysql service: net stop mysql to
access mysql: mysql -h localhost -P 3306 -u root -p password
Check parameters: show variables;
set parameters: set parameter name='value';
check current storage engines: show engines;
modify current storage engines: set default_storage_engine=innodb;
check status: SHOW STATUS;
check version: SELECT VERSION();

2. User permissions

Create user: create user `test`@`localhost` identified by '123456';
modify password: alter user `test`@`localhost` identified by '123456'; 
delete user: drop user `test`@`localhost`;
refresh User: flush privileges;
grant permissions: grant all on *.* to `test`@`localhost`;
revoke permissions: revoke all on *.* from `test`@`localhost`;
query the current user: select USER();
View user permissions: show grants for Fox@localhost;
query all users in the database: SELECT * FROM mysql.user;


Four, data definition language DDL

1. Build a library

Check all the libraries: show databases;
check the current database: select database();
modify the database: ALTER DATABASE mybase CHARACTER SET UTF8;
create a database: create database database name character set utf8;
check the database statement: show create database database name;
delete Library: drop database database name;
switch database: USE mybase;

2. Build a table

Check all tables: show tables;
create table: create table exam(
    id INT(11) PRIMARY KEY AUTO_INCREMENT, - primary key auto increment
    name VARCHAR(20) DEFAULT NULL, - default is empty
    English INT,
    sal DOUBLE(7, 2), --Integer digit 7, decimal digit 2
    Math int NOT NULL --Non -empty
);
Add primary key: alter table stu2 add PRIMARY key (id,`name`); --Specify id name together as primary key to
add default value : Alter table stu2 alter COLUMN `gender` set DEFAULT'm';
add unique constraint and non-null constraint: ALTER TABLE exam MODIFY NAME VARCHAR(21) UNIQUE NOT NULL;
lookup structure: desc table name
lookup table statement: show create table table name;
delete table: drop table table name;
modify table name: RENAME TABLE exam TO score;
modify the character set of the table: ALTER TABLE score CHARACTER SET GBK;
create table stu4 like stu3; - completely copy the table structure, except for data
SHOW GLOBAL VARIABLES LIKE'innodb_force_primary_key'; - to see if the mandatory primary key is turned on
SET GLOBAL innodb_force_primary_key=off; - to turn off the mandatory primary key
mysql8 will enable mandatory primary key constraints by default. You must turn off the mandatory primary key to use the following statement. ps: General companies are not allowed to turn off mandatory primary keys.
create table stu5 as select * from stu3;-- Copy all data in the table to the new table, except the primary key cannot be copied
create table stu6 as select id, name from stu3;-- Copy some fields of the original table to the new table, except for the primary key
create table stu7 as select * from stu3 where 1=0;-copy the table structure of the original table to the new table, except for the primary key

3. Build index

Create the table when creating:
create table book(
isbn varchar(50) not null,
bookname varchar(100) not null, 
price decimal(8,2),
author varchar(50),
publishhouse varchar(50),
summary text,
PRIMARY key `pk_isbn`(`isbn`), - Primary key index
UNIQUE index `idx_bookname`(`bookname`), - Unique index
index `idx_author`(`author`), - General index
FULLTEXT index `ft_summary`(`summary `) - Full-text index
);

create statement:
create index `idx_author` on `book`(`author`); - ordinary index
create UNIQUE index `idx_bookname` on `book`(`bookname`); - unique index
create FULLTEXT index `ft_summary` on ` book`(`summary`); - Full text index

alter table statement:
alter table book add index `idx_author`(`author`); - ordinary index
alter table book add UNIQUE index `idx_bookname`(`bookname`); - unique index
alter table book add FULLTEXT index `ft_summary` (`summary`); - Full-text index

Delete index:
drop index index name on table name;

View index:
SHOW INDEX FROM table name;

4. Build a view

create view view name (field list) as select field list from ......
CREATE VIEW v_studentCourseScore (
    studentno, NAME, coursename, score) AS SELECT
    a.sid, a.`name`, b.cname, c.number
FROM student a, course b, score c
WHERE a.sid = c.sid AND b.cid = c.corse_id;

Delete view:
drop view view name;

5. Modify table fields

Add field: alter table stu2 add major VARCHAR(20);
modify data type: alter table stu2 MODIFY major char(20);
modify field name: alter table stu2 change major professional char(20);
delete field: alter table stu2 drop professional ;


Five, data manipulation language DML

1. Insert data

Insert into: insert data directly, insert
a full field value: insert into stu2 values(1,'zhangsan','m',20);
insert a partial field value: insert into stu2(id,name) values(3,'wangwu ');
Insert multiple data at once: insert into stu2(id,name) values(5,'zhao7'),(6,'zhao8'),(7,'zhao9');
insert the result of querying a table : Insert into stu3(id,name,gender,age) select id,name,gender,age from stu2;

Replace into: first check if it exists, update if it exists, and insert if it does not exist.
Replace into table name (field list) values ​​(value list)
Replace into table name (field list) select field list from table [where constraint]
Replace into table name set field=value, field=value

2. Update data

update table name set field=value, field=value where constraint conditions; --update eligible rows
update table name set field=value, field=value; --update all rows

3. Delete data

delete from table name where constraint conditions; --delete records that meet the conditions, data can be rolled back
delete from table name; --delete all records, data can be rolled back
truncate table table name; --empty table, data cannot be rolled back.


Six, data query language DQL

1. Select syntax format

select field list from table 1, table 2 where constraint condition group by grouping field having second filter condition order by sort condition limit quantity

2. Basic SQL statements

Query all data: select * from stu;

Take the alias as: select name as name from stu t; - Query the column name and take the alias name as the name, and the table name stu as t;

Sort order by: asc (ascending order)/desc (descending order), the default is ascending order.
select * from stu2 order by age desc; - specify descending order
select * from stu2 order by age asc, weight desc; - sort by multiple fields

limit keyword:
select * from stu2 limit 2; - return to the first 2 rows
select * from stu2 limit 1,2; - return to the second and third, 1 is the index, the index starts from 0


Distinct eliminates duplicate records: select DISTINCT name from stu2; --return records with different names
select DISTINCT name, age from stu2; - return records with different names and ages

where conditions:

Relational operators: = >=> <= <!= <> <=>
select * from stu2 where weight = null; - null values ​​cannot be constrained here, and no results can be found
select * from stu2 where weight < => null; - can find all records whose weight is empty
select * from stu2 where weight >=100; - find students whose weight is greater than or equal to 110

Range query: between and, not between and and in, not in
select * from stu2 where weight BETWEEN 110 and 125; - range query suitable for continuous values
select * from stu2 where weight in(110,120,125); - suitable for discrete values Range query

Fuzzy matching: like, not like
select * from stu2 where name like'zhang%'; - all names beginning with zhang
select * from stu2 where name like'zhang_'; - only 1 character after the beginning of zhang
First name select * from stu2 where name like'%zhang%';--- contains the name of zhang
select * from stu2 where name like'_zhang_';--- is zhang in the middle, and the name is 1 character before and after

Determine whether it is empty: is null, is not
select * from stu2 where weight is null; - is empty
select * from stu2 where weight is not null; - is not empty

Multi-condition query: and, or
select * from stu2 where age> '18' and sex='男'; - query records whose age is greater than 18 years and whose gender is male
select * from stu2 where age> '18' or sex= 'Male'; - Query records whose age is greater than 18 or whose gender is male

3. Common functions

Mathematical function:
select abs(-1.45); - take the absolute value, output 1.45
select FLOOR(1.5); - round down, output 1
select CEILING(1.5); - round up, output 2
select mod( 2,3); - Modulo
select TRUNCATE(156.567,2); --Truncate to 2 decimal places, output 156.56
select TRUNCATE(156.567,0); --Truncate to integer, output 156
select TRUNCATE(156.567,-2 );
--Truncate to 2 integers, output 100 select ROUND(156.567,2); --Round to 2 decimal places, output 156.57
select ROUND(156.567,0); --Round to integers, output 157
select ROUND(156.567 ,-2); --Round to the integer 2 digits, output 200

String function:
select CONCAT('i','have','a','dream'); - String concatenation
select CONCAT_WS('','I','have','a','dream' ); - String concatenation and each word separated by spaces
select left('Hunan Changsha',3); - Take the left 3 characters
select right('Hunan Changsha',3); - Take the right 3 characters
select length('abcdefg'); - Display the length of the string
select ltrim('Hunan Changsha Wuyi Square'); - Remove the left space
select rtrim('Hunan Changsha Wuyi Square'); - Remove the right space
select trim('Hunan Changsha Wuyi Square'); - remove the leading and trailing spaces
select UPPER('abcd'); - lowercase to uppercase
select LOWER('ABCD'); - uppercase to lowercase
SELECT SUBSTR('123abcdABCD Hunan Changsha' ,4,3); - Start from the 4th digit, intercept 3 digits, and output abc
SELECT ename,IFNULL(COMMIT,0) FROM emp; - If COMMIT has a null value, it will be displayed as 0
SELECT ename,CAST(sal AS INT) FROM emp; - convert the sal field to int type output
SELECT ename,COALESCE(USER,COMMIT,0) FROM emp; - Take the value of user first, if user is null, take the value of commit, and if commit is also null, output 0

Time functions:
select CURDATE(); - check current date 2020-11-18
select CURDATE() +0; - check current date 20201118
select CURTIME(); - check current time 17:55:05
select DATE_ADD(' 2018-02-10 10:10:10',INTERVAL 1 day); - plus 1 day
select DATE_ADD('2018-02-10 10:10:10',INTERVAL -1 MONTH); - minus 1 month
select DATE_ADD('2018-02-10 10:10:10',INTERVAL -1 YEAR); - minus 1 year
select DAYOFWEEK('2020-11-29 10:10:10'); - query the day of the week, output 1, 1 represents Sunday
select DAYNAME('2020-11-29 10:10:10'); - Query the English name of the week, and output Sunday
select MONTHNAME('2020-01-29 10:10:10');- -Query the English name of the month and output January
select NOW(); - Query the current time
select UNIX_TIMESTAMP(); - Query the current timestamp

Aggregate functions:
select 
max(score), - maximum
min(score), - minimum
avg(score), - average
sum(score), - sum
count(studentNO), - total number
from score;

Process function:
SELECT IF(500<1000, 5, 10); - If the condition of 500<1000 is true, output 5, otherwise output 10;
SELECT (CASE
WHEN state='3' THEN'Fail'
WHEN state='5' THEN 'success' 
the eLSE 'other' END) 'state'
the FROM cm_job; - if state = '3' output failure, state = '5' success output

Group query:
Syntax: Select [Group field list,] Aggregate statistics function (...)
From Table 1, Table 2 where Constraint
Group by Grouping field having Constraint
order by Sorting field sorting conditions
Example: query the number of passers in each course exceeds 3 Individual, course number, number of people
select major,count(*) num from student.student 
where score >=60 GROUP BY major having num>3;

4. Connect query

Cartesian product
select * from student a, class b;

等值连接
select a.name,b.classname from student a,class b where a.classno=b.classno;

Inner connection: the result set that meets the connection condition.
select a.name,b.classname from student a,class b on a.classno=b.classno;
select a.name,b.classname from student a,class b on a.classno<>b.classno;

Left join: Based on the left table, the result will display all the records in the left table that match the records in the right table, and the right table does not match with NULL instead.
select a.classname,b.name,c.score from class a LEFT JOIN student b 
on a.classNO=b.classNO left join score c on b.studentNO=c.studentNO 
where b.gender='m';

Right join: Based on the right table, the result will show all records in the right table that match the left table, and the left table does not match with NULL instead.
select a.`name`,b.classname
from student a right join class b on a.classNO=b.classNO;

Self-connection: the table connects with itself
select a.empno leader number, a.ename leader name, a.job leader position
, b.empno employee number, b.ename employee name, b.job employee position
from emp a, emp b
where a.empno=b.mgr;

5. Subquery

Scalar quantum query: The returned result is 1 column and 1 row
-query information about the student with the heaviest weight
select * from stu2 where weight=
(select max(weight) from stu2);

Lie sub query: sub query returns a single column and multiple rows of results
-to find out the student information with the highest Chinese score
select * from student where studentno in(
select s2.studentno
from score s2,course c2 where s2.courseno=c2.courseno and s2.score =(
select s.score
from score s,course c
where s.courseno=c.courseno and c.coursename='yuwen'
order by s.score desc limit 1) and c2.coursename='yuwen')

Row subquery: return the results of a single row and multiple columns
. Get the gender, class number, name, etc. according to the student ID, and then get the detailed information of the student
select * from stu2 where (gender,class,name)=
(select gender,class,name from stu2
where id=1);

Table subquery: return results with multiple rows and multiple columns.
Find information about students with the same score in each course
select * from student where studentno in(
select s2.studentno from score s2, course c2 where s2.courseno=c2.courseno and(c2. courseno,s2.score) in(
select c.courseno,s.score from score s, course c where s.courseno=c.courseno GROUP BY c.coursename,s.score having s.score>=2));

6, Exists predicate

If it exists, the following sql will be executed, and if it does not exist, the following sql will not be executed.
If a student's language score is less than 40, update the score to 60.
update score set score=60 where score<=40 and courseno =
(select courseno from course where coursename='yuwen');

7, derived table

Use the result returned by the sql statement as a table to associate with other tables, and perform the query again. This is a derived table.
Information about the student with the highest score in each course.
select * from student where studentno in(
select a.studentno 
from score a,(select courseno,max(score) ma from score group by courseno) b
where a.courseno=b.courseno and a.score=b.ma);

8. Set operations

UNION: two query statements merge the results together and remove duplicate rows
UNION ALL: two query statements merge the results together without removing any rows
SELECT a.deptno FROM dept a UNION SELECT deptno b FROM emp;-- query Must be the same

 

Guess you like

Origin blog.csdn.net/weixin_46285621/article/details/109983185