Mysql
1, Operation database: CRUD
-
C (Create): Create
-
Create database:
-
create database Database name;
-
-
Create a database. When it is judged that it does not exist, create it again:
-
create datsbase if not exists Database name;
-
-
Create the database and specify the character set:
-
create database Database name character set Character set name;
-
-
Exercise: create a db4 database, determine whether it exists, and specify the character set as gbk:
-
create database if not exists db4 character set gbk;
-
-
-
R (Retrieve): query
-
Query the names of all databases:
-
show databases;
-
-
Query the subset of a database: query the creation statement of a database:
-
show create database Database name;
-
-
-
U (Update): modifying
-
Modify the character set of the database:
-
alter database Database name character set Character set name;
-
-
-
D (Delete): Delete
-
Delete database:
-
drop database Database name;
-
-
Judge whether the database exists, and then delete it
-
drop database if exists Database name
-
-
-
Use database
-
Query the name of the database currently in use
-
select database();
-
-
Use database:
-
use Database name
-
-
2, Operation table: CRUD
-
C (Create): Create
-
Syntax:
create table Table name( Column name 1 data type 1, Column name 2 data type 2, Column name 3 data type 3, ....... Listing n data type n --Note: the last line does not contain a comma );
-
Database type:
-
Int (integer type): age int
-
Double (decimal type): score double(5,2)
-
(5,2) indicates that there are 5 decimal places, and two decimal places are reserved
-
-
Date (date): only include year, month and day, yyyy mm DD
-
datetime (date): including month, day, hour, minute and second, yyyy MM DD HH mm SS
-
timestamp (time error type): including yyyy MM DD HH mm SS
-
If this field is not assigned a value in the future, or the value is null, the current system time will be used by default and the value will be assigned automatically
-
-
Varchar (string type): name varchar(20) indicates the maximum 20 characters of the name
-
-
-
R (Retrieve): query
-
Query the names of all tables in a database:
-
show tables;
-
-
Query the character set of a table:
-
show create table Table name;
-
-
Query table structure:
-
desc Table name;
-
-
-
U (Update): modifying
-
Modify table name:
-
alter table Table name rename to New table name;
-
-
Modify the character set of the table:
-
alter table Table name character set Character set name;
-
-
Add a column:
-
alter table Table name add Column name data type;
-
-
Delete a column:
-
alter table Table name drop Listing;
-
-
Modify column name and data type:
-
alter table Table name modify Column name new data type; --Modify data type only
-
alter table Table name change Column name new column name new data type; --Modify both column names and data types
-
-
-
D (Delete): Delete
-
drop table Table name;
-
drop table if exists Table name;
-
3, DML: data in addition, deletion and modification table
-
Add data:
-
insert into Table name(Column name 1,Column name 2,....,Listing n) values(Value 1,Value 2,....,value n);
-
-
Delete data:
-
delete from Table name [where condition];
-
be careful:
-
To delete all records:
-
delete from table name-- Not recommended. You can delete as many records as you have
-
truncate table name-- Recommended as like as two peas, first delete the sheet and create a blank table.
-
-
-
-
Modify data:
-
update table Table name set Column name 1=Value 1,Column name 2=Value 2,.....[where condition];
-
be careful:
-
If no conditions are added, all the data in the table will be modified
-
-
4, DQL: query records in a table
-
Syntax:
select Field list from Table name list while Condition list group by Group list having Conditions after grouping order by sort limit Paging limit
-
Basic query:
-
Query of multiple fields:
-
select Field name 1,Field name 2.... from Table name;
-
-
Remove duplicates:
-
select distinct Field name from Table name;
-
-
Calculation column: generally, four operations can be used to calculate the values of some columns (generally, only numerical operations will be performed)
-
select name,math,english,ifnull(math,0)+ifnull(english,0) from Table name;
-
be careful:
-
Null participates in the operation, and the calculation results are null
-
Solution: ifnull(english,0): it means that if the value of english is null, its value is 0
-
-
-
Alias: as (can also be omitted, replaced by a space)
-
select name,math (as) mathematics,english (as) English,math+eglish (as) Total score from Table name;
-
-
-
Condition query:
-
Syntax: where condition
-
Operator:
-
between.......and......
-
in (set)
-
is (not) null
-
and or & & or or not or!
-
like: fuzzy query
-
Placeholder:: Single arbitrary character%: zero or more arbitrary characters
-
select * from stu where like "horse%" --Query the information of the person surnamed ma select * from stu where like "_turn%" --The second word in the query name is the humanized person select * from stu where like "___" --Query people whose names are three words
-
-
-
-
Query sorting:
-
Syntax:
-
order by Sort field 1 sort by 1 , Sort field 2 sort by 2 ......
-
-
Sort by:
-
ASC: ascending (default)
-
DESC: descending
-
-
be careful:
-
If there are multiple sorting conditions, the second condition will be judged only when the previous condition values are the same
-
select * from stu order by math ASC , english DESC;
-
In ascending order of math scores, if the math scores are the same, in descending order of English scores
-
-
-
Aggregate function:
-
Count: count
-
max: calculate maximum
-
min: calculate the minimum value
-
sum: Calculation and
-
avg: calculate average
be careful:
-
Calculation of aggregate function, excluding null values
-
Solution: 1. Select a column that does not contain null for calculation: primary key, count(*) 2. ifnull(english,0)
-
-
-
Group query:
-
Syntax:
-
group by group field
-
-
-
Paging query:
-
Syntax:
-
Index starting from limit, number of queries per page
-
-
Formula: starting index = (current page number - 1) * number of queries per page
-
eg:
--Three records per page select * from stu limit 0,3; --first page select * from stu limit 3,3; --Page 2 select * from stu limit 6,3; --Page 3
-
5, Restraint
-
Non NULL constraint: not null, value cannot be null
-
Add constraints when creating tables:
-
create table stu( id int, name varchar(20) not null; )
-
-
Add constraints after creating tables:
-
alter table stu modify name varchar(20) not null;
-
-
To delete a non empty constraint:
-
alter table stu modify name varchar(20);
-
-
-
Unique constraint: unique, the value cannot be repeated
-
Adding constraints when creating tables: omitted
-
To add a unique constraint after creating a table:
-
alter table stu modify phone_num varchar(20) unique;
-
-
Delete unique constraint:
-
alter table stu drop index phone_num;
Note: in MySQL, the value of a column limited by a unique constraint can have multiple null values
-
-
-
Primary key constraint: primary key, non empty and unique
-
Adding constraints when creating tables: omitted
-
Add constraints after creating tables:
-
alter table stu modify id int primary key;
-
-
To delete a primary key constraint:
-
alter table stu drop peimary key;
-
-
Automatic growth:
-
When creating a table, add a primary key constraint and complete the automatic growth of the primary key: omitted
-
Add primary key auto growth after table creation:
-
alter table stu modify id int auto_increment;
-
-
Delete automatic growth:
-
alter table stu modify id int; --This will not delete the primary key. Delete the primary key with drop
-
-
-
-
Foreign key constraint: foreign key, which associates the table with the table to ensure the correctness of the data
-
Add foreign keys when creating tables:
create table Table name( ..... Foreign key column constraint Foreign key name foreign key (Foreign key column name) references Main table name(Main table column name) );
-
To add a foreign key after creating a table:
-
alter table employee add constraint emp_dep_id foreign key dep_id references department(id);
-
-
To delete a foreign key:
-
alter table employee drop foreign key emp_dep_id;
-
-
Cascade operation:
-
alter table employee add constraint emp_dep_id foreign key (dep_id) references department(id) on update cascade on delete cascade;
-
on update cascade: if the column name of the main table is updated, the foreign key column name is updated randomly
-
on delete cascade: cascade delete: if the name of the main table column is deleted, the foreign key column name will be deleted randomly
-
-
6, Multi table query
-
Internal connection query:
-
Implicit concatenation: use the where condition to eliminate useless statements
-
select t1.name, --Name of employee table t1.gender, --Gender of employee table t2.name -Name of department table from emp t1, dept t2 where t1.'dept_id' = t2.'id';
-
-
Explicit inner join
-
select * from emp [inner] join dept on emp.'dept_id' = dept.'id';
-
-
-
External connection query:
-
Left outer connection:
-
select Field list from Table name 1 left [outer] join Table name 2 on condition; -- The query is all the data in the left table and the intersection part
-
-
Right outer connection:
-
select Field list from Table name 1 right [outer] join Table name 2 on condition; -- The query is all the data in the right table and the intersection part
-
-
-
Subquery:
-
The result of subquery is single row and single column:
select avg(salary) from emp; --3000 select * from emp where salary < 3000; combination: select * from emp where salary < (select avg(salary) from emp);
-
The result of subquery is multi row and single column:
select id from dept where name='Finance Department' or name='Marketing Department'; --2,3 select * from emp where dept_id = 2 or dept_id = 3; combination: select * from emp where dept_id = (select id from dept where name='Finance Department' or name='Marketing Department');
-
The result of subquery is multi row and multi column:
-
--A subquery can be used as a virtual table
-- The entry date of the employee is 2011-11-11 Subsequent employee information and department information -- Subquery: select * from dept t1,(select * from emp where emp.'join_date' > '2011-11-11') t2 where t1.'id' = t2.'dept_id'; --Internal connection: select * from emp t1,dept t2 where t1.'dept_id' = t2.'id' and emp.'join_date' > '2011-11-11';
-
-
7, Business
-
Basic introduction to transaction:
-
Concept:
-
If a business operation with multiple steps is managed by a transaction, these operations either succeed or fail at the same time
-
-
Operation:
-
Start transaction: start transaction
-
Rollback: rollback (a problem is found and the transaction is rolled back)
-
Commit: commit (if there is no problem with execution, commit the transaction)
-
-
There are two ways to commit a transaction:
-
Auto submit:
-
MySQL database is automatically committed by default. A DML (add, delete, modify) statement will automatically commit a transaction
-
-
Manual submission:
-
Oracle database is manually committed by default. You need to start the transaction first and then commit manually
-
-
To modify the default commit method of a transaction:
-
To view the default commit method of a transaction:
-
select @@autocommit; --1 for automatic submission and 2 for manual submission
-
-
To modify the default submission method:
-
set @@autocommit = 0;
-
-
-
-
-
Four characteristics of transactions:
-
Atomicity: it is the smallest indivisible operation unit, which either succeeds or fails at the same time
-
Persistence: after the transaction is committed or rolled back, the database will persist the data
-
Isolation: multiple things are independent of each other
-
Consistency: after the transaction operation, the total amount of data remains unchanged
-
8, Backup and restore of database
-
Backup: mysqldump -u user name - p password database name > saved path
-
Restore: login Database > create key database > Use Database > execute file (source file path)
9, DCL
-
Manage users:
-
Add user:
-
create user 'user name'@'host name' identified by 'password';
-
-
Delete user:
-
drop user 'user name'@'host name';
-
-
Query user:
-
1. Switch to MySQL database: use mysql; 2. Query user table: select * from user;
-
-
Modify user password:
-
update user set password = password('New password') where user = 'user name'; set passwprd for 'user name'@'host name' = password('New password');
-
-
-
jurisdiction:
-
Query authority:
-
show grants for 'user name'@'host name';
-
-
Grant permissions:
-
grant Permission list on Database name.Table name to 'user name'@'host name';
-
-
Revoke permissions
-
revoke Permission list on Database name.Table name from 'user name'@'host name';
-
-