当前位置:网站首页>Knowledge points of MySQL (12)
Knowledge points of MySQL (12)
2022-07-24 15:43:00 【Flag: roll king!】
One 、 On the column :AUTO-INCREMENT
effect : The value of a field increases automatically
Features and requirements :
- A table can only have at most one self growing column
- When a unique identifier or sequential value needs to be generated , Settable growth
- The column of the self growing column constraint must be a key column ( Primary key column 、 Unique key column )
- The data type of a column with a self increasing constraint must be an integer type
- If the auto increment column specifies 0 and NULL, It will increase automatically based on the current maximum , If the auto increment column manually specifies a specific value , Direct assignment to a specific value
Code implementation :
1, stay CREATE TABLE add
# Build table
creat table test4(
id int primary key auto_increment,
last_name varchar(15)
);
# add to
insert into test4(last_name)
values('TOM');
select * from test4;( Be careful : In development , Once the primary key field is declared to have AUTO_INCREMENT, When we add data , Don't assign values to the fields corresponding to the primary key )
2, stay ALTER TABLE add
# Build table
create table test5(
id int primary key,
last_name varchar(15)
);
# Check the information
desc test5;
# Add self increasing
alter table test5 modify id int auto_increment;
desc test5;Two 、FOREIGN KEY( Foreign keys ) constraint
effect : Limit the referential integrity of a field in a table
1, stay CREATE TABLE add
# Create the main table first
create table dept1(
dept_id int,
dept_name varchar(15)
);
# Add primary key constraint
alter table dept1 add primary key(dept_id);
desc dept1;
# Creating slave tables
create table emp1(
emp_id int primary key auto_increment,
emp_name varchar(15),
department_id int,
# Table level constraints
constraint fk_emp1_dept_id foreign key(department_id) references dept1(dept_id)
);
desc emp1;
select * from information_schema.table_constraints where table_name='emp1';demonstration :
# Add failure
insert into emp1 values(1001,'TOM',10);
# Add success ( In the main table dept1 Add 10 After department No , You can add 10 Employees of Department )
insert into dept1 values(10,'IT');
insert into emp1 values(1001,'TOM',10);
# Delete failed
delete from dept1 where dept_id=10;
# Update failed
update dept1 set dept_id=20 where dept_id=10;2, Constraint level

demonstration :on update cascade on delete set null
# Create the main table
create table dept(
did int primary key, # Department number
dname varchar(50) # Department name
);
# Create from table
create table emp(
eid int primary key, # Employee number
ename varchar(5), # Employee name
deptid int, # Employee's Department
foreign key (deptid) references dept(did) on update cascade on delete set null
# Set the modification operation to cascade modification level , Set the delete operation to set null Grade
);
# Add data
# First add the main table data
insert into dept values(1001,' Academic Building ');
insert into dept values(1002,' Finance Building ');
insert into dept values(1003,' Consulting building ');
# Add data from table
insert into emp values(1,' Zhang San ',1001); # When adding this data , Required department table 1001 department
insert into emp values(2,' Li Si ',1002);
insert into emp values(3,' Wang Wu ',1003);
select * from dept;
select * from emp;
# Update and modify
update dept set did=1004 where did=1002;
select * from dept;
select * from emp;
# Delete
delete from dept where did=1004;
select * from dept;
select * from emp;Conclusion : For foreign key constraints , It's better to use :‘on update cascade on delete restrict’ The way
3、 ... and 、CHECK( Check ) Constraints and DEFAULT( The default value is ) constraint
CHECK Constraint action : Check whether the value of a field matches XX requirement , Generally refers to the range of values .
# Build table
create table test6(
id int,
last_name varchar(15),
salary decimal(10,2) check (salary>2000)
);
# Add data
# Add failure
insert into test6 values(1,'TOM',1500);
select * from test6;
# Add success
insert into test6 values(1,'TOM1',2500);
select * from test6;DEFAULT Constraint action : Give a field / Specify a default value for a column , Once the default value is set , When inserting data , If this field does not show assignment , The default value is assigned .
Four 、 View
1, Common database objects

2, View understanding
View function : On the one hand, it can help us use some tables instead of all tables , On the other hand, you can also make different query views for different users .
View understanding :
- View is a virtual table , There is no data in itself , Takes up very little memory space , It is SQL An important concept in
- Views are built on existing tables , The tables on which the view is built are called base tables
- The creation and deletion of views only affect the view itself , It does not affect the corresponding base table , But when the data in the view is added 、 When deleting and modifying operations , The data in the data table will change accordingly , vice versa .
- The statement that provides data content to the view is SELECT sentence , Views can be understood as stored SELECT sentence
- View , It is a form of providing users with base table data . Usually , Small project database can not use views , But on big projects , And when the data table is complex , The value of view is highlighted , It can help us put the result set of frequent queries into the virtual table , Improve efficiency .
3, Create view (VIEW)
# preparation
create database dbtest1;
use dbtest1;
create table emp as select * from atguigudb.employees;
select * from emp;
desc emp;
# For single table
# How to determine the field names in the view 1:
create view vu_emp1 as select employee_id emp_id,last_name lname,salary from emp;
# The alias of the field in the query statement will be used as the name of the field in the view
select * from vu_emp1;
# How to determine the field names in the view 2:
create view vu_emp2(emp_id,name,monthly_sal) # The number of fields in parentheses is the same as SELECT The number of fields in the is the same
as select employee_id ,last_name ,salary from emp;
select * from vu_emp2;
# For multiple tables
create view vu_emp_dept
as
select e.employee_id,e.department_id,d.department_name
from emps e join depts d
on e.'department_id'=d.'department_id';
select * from vu_emp_dept;Create a view based on the view :
create view vu_emp3
as
select employee_id,last_name
from vu_emp1;
select * from vu_emp3;4, View view
grammar 1: View the table objects of the database 、 View objects
show tables;
grammar 2: View view structure
describe View name ;
grammar 3: View the attribute information of the view
show table status like ' View name ';
grammar 4: View view Detailed definition information of
show create view View name ;
5, Update the data in the view ( There must be a one-to-one relationship between the rows in the view and the rows in the underlying basic table )
# Select View
select * from vu_emp1;
select employee_id,last_name,salary from emps;
# Update view data , This will lead to the modification of data in the base table
update vu_emp1 set salary=2000 where employee_id=101;
# Updating the data in the table will also lead to the modification of the data in the view
update emps set salary=10000 where employee_id=101;
# Delete data from view , It will also cause the data in the table to be deleted
delete from vu_emp1 where employee_id=101;
Of course, there are some views that cannot be updated :

( Be careful : Although view data can be updated , But on the whole , View as virtual table , It is mainly used to facilitate query , It is not recommended to update the data of the view , Modification of view data , It is done by operating the data in the actual data table )
6, Modify the view
# The way 1
create or replace view vu_emp1
as
select employee_id,last_name,salary,email from emps where salary>7000;
# The way 2
alter view vu_emp1
as
select employee_id,last_name,salary,email,hire_data from emps;边栏推荐
- R语言ggplot2可视化:ggplot2可视化基本散点图(scatter plot)、通过在theme_bw中指定参数base_size来改变轴标签的大小、并控制网格线和轴标签的大小
- What is the ranking of good securities companies? Is online account opening safe
- Sklearn.metrics module model evaluation function
- YOLO5Face:为什么要重新发明人脸检测器
- Dynamics 365: how to get the threshold value of executemullerequest in batch requests
- 降噪蓝牙耳机哪个好?性价比最高的降噪蓝牙耳机排行
- pip 安装报错 error in anyjson setup command: use_2to3 is invalid.
- [acwing] 909. Chess game
- Analysys analysis "2022 China data security market data monitoring report" was officially launched
- celery 启动beat出现报错ERROR: Pidfile (celerybeat.pid) already exists.
猜你喜欢

Memorythrashing: Tiktok live broadcast to solve memory dithering practice
![Error reporting [project error reporting]](/img/7a/322ba86c13667a62c484b2329ac617.png)
Error reporting [project error reporting]

【SWT】滚动容器实现商品列表样式

Research on stability of time-delay systems based on Lambert function

Using JS to implement click events

降噪蓝牙耳机哪个好?性价比最高的降噪蓝牙耳机排行

Kubectl_ Easy to use command line tool: Oh my Zsh_ Tips and tricks

Automatic derivation of pytorch

从哪些维度评判代码质量的好坏?如何具备写出高质量代码的能力?

Join parameter processing and @param
随机推荐
【量化测试】
Varnish4.0缓存代理配置
Lsyncd set up synchronous image - use lsyncd to realize real-time synchronization between local and remote servers
pip 安装报错 error in anyjson setup command: use_2to3 is invalid.
请问好的券商的排名?网上开户安全吗
SQL row to column, column to row
[TA frost wolf \u may - hundred people plan] Figure 3.4 introduction to delayed rendering pipeline
Azure key vault (1) Introduction
Database learning – select (multi table joint query) [easy to understand]
[shaders realize pixelate mosaic effect _shader effect Chapter 7]
Windows10安装免安装版redis
Dynamics crm: sharing records for users and teams
C. Recover an RBS
Join parameter processing and @param
Automatic derivation of pytorch
Using JS to implement click events
R language Visual facet chart, multivariable grouping nested multilevel t-test, and specify reference level, visual multivariable grouping nested multilevel faceting boxplot, and add significance leve
Multus of kubernetes multi network card scheme_ CNI deployment and basic use
微调LayoutLM v3进行票据数据的处理和内容识别
Research on stability of time-delay systems based on Lambert function