01-Relational database standard language

Some concepts of database

Behavior: represents what the object can do

Objects-Are there any relationships between objects? is--a (inherited) has (owned) use (used)

User objects: user name, login name, password, gender, home address, contact phone number, date of birth, personal photo

In the database, what is actually stored is the value of the attribute of the object.

老师 - 学生(has)  父母 - 子女(has)
职员 - 项目经理,程序员(继承)

So in the database, in fact, more research: association relationship (has), inheritance relationship (is--a)

Non-relational database (NoSQL: redis, hbase, memcache ...), when stored: you can directly store it as an object

NoSQL != no sql  === NOT Only SQL
NoSQL 看重存储效率(存储是否快捷)
关系型数据 看重的数据之间的关系
稍微复杂点的系统:关系型数据(关系) + NoSQL(快速的存取数据)

Primary key: a unique identifier specifically used to distinguish the data in the table: id, once determined, it cannot be modified

The characteristics of the primary key field: can not have any business meaning: ID card, phone number ... The answer is: none

1代身份证:15位    2代身份证:18位

Foreign key: a field specifically used to determine the relationship between the table and the data in the table

In relational databases: inheritance (less, special scenarios: type of staff, classification of roles), association

关联关系:
1对1 例如:中国的夫妻关系    
1对n 例如:某一个老师跟学生      血缘关系下的父母与子女
n对n 例如:系统中的角色和权限
这些关系中,最常见的:1对n   比较少的:1对1  n对n

Association relationships are often limited to certain special scenarios to be effective

SQL: Structured Query Language

Function: a standard language specially used for communication between the database client and the server, for example: Chinese, English. Can help us: store, query, and analyze data in the database through the DBMS, and help us manage the database. Java, PHP, .net, python ... Programs written can also be used as our clients and also know SQL. The SQL standard is constantly changing, and its impact: DBMSs that extend many different SQL syntaxes are out. Some SQL syntax of MYSQL is different from SQLServer and Oracle

SQL is not case sensitive, CREATE == create

SQL is classified into 4 types of languages

DDL (Data Define Language): Create, delete, modify (databases, tables, columns, indexes, stored procedures, views, functions, triggers ...) Keywords used: create, alter, drop ...

DML (Data Manipulation Language): Add, modify, delete (data in the table) Keywords used: insert, update, delete, trancate ...

DQL (Data Query Language): Query (data in the table) Keyword used: select

DCL (Data Control Language): Key words used to grant users permission to operate databases and tables: grant, revoke ...

Instances created by the pattern

The definition mode is actually to define a namespace, in this space you can further define the database objects contained in the mode, such as basic tables, views, indexes
Log in with the sa account, create a database named studentdb, and then create a schema named sch1
Ready to work
create database studentdb
use studentdb
go
create login zhou1 with password=‘mypassword123’
go
create user zhou1 for login zhou1
Create and delete
create schema sch1 authorization zhou1
drop schema sch1

The basic syntax of the table

Syntax for creating tables
Create Table Users
{
vUserName varchar(18) Not NULL,
vPassword varchar(20) Not NULL
}
Create student table (with constraints and primary key)
Create Table Student
{
Sno char(10) NOT NULL Constraint PK_stu_NO Primary Key,
Sname char(20) NOT NULL,
Ssex cahr(2) NOT NULL Constraint CK_Stu_Sex Check(Ssex in('男','女')),
Sage tinyint Constraint CK_Stu_Age Check(Sage between 1 and 80),
Tel char(15) NOT NULL
}
Modify student table
Alter Table Student Drop Constraint CK_Stu_Age
Remove the constraint on the Sage field
Alter Table Student Drop Column Sage
Delete Sage column
Alter Table Student Add dBirth datetime
Add column
Alter Table Student Alter Column Smajor varchar(20)
Modify column field size
drop table student
Delete previous student list

Single table query

concept
SELECT  表上哪些列显示
*表示所有列 
//投影运算 指的是选择部分列数据
//友好列标题 SELECT Sno as 学号
//top关键字 SELECT Top 3 * from Student 只显示前3条数据
FROM 这个表来源
WHERE 这个表的情况,进行筛选
Retrieve student information for age 20
select * from student where Sage=20
and connect multiple conditions
select * from student where ssex='女'and sage>21
or indicates that a condition is met, between and between conditions, not between and inverse conditions
select sno,sname,ssex from student whrer sno between '2' and '4'
in retrieves a list of values
select * from teacher where tropt in('教授','副教授')
distinct means that the same information is not retrieved
select distinct tropt from teacher
like fuzzy search
select sname,sdept from student where sdept like'%学%'
@ A string matches an underscore
select sname,sdept from student where emall like '__@%'
is null field is empty
select *from student where low is null
is not null field is not empty
select *from student where high is not null
GROUP BY, grouping according to the selection after by for group statistics
Classify courses according to required and optional courses, and count the number of courses in each category
select xklb as 类别,count(cname) as 数量 from course group by xklb 
HAVING
ORDER BY ASC||DESC
ASC表示升序,DESC表示降序
select *from student order by sage desc
select *from student order by sage desc,sno asc在sage相同情况下按snow升序对比排列
COUNT 
count函数返回匹配行数
select count(*) from teacher where tropt=‘教授’
Aggregate functions MAX, MIN, AVG
显示教师的最大最小平均年龄
select max(tage),min(tage),avg(tage) from teacher 
指定条件求和 
select sum(credit) from course where xklb='必修' 对course表中的必修课的学分进行求和
Hybrid application
select smajor,ssex,count(sno) from student group by Smajor ,sex order by count(sno) desc
对student表,按照专业和性别进行分组,显示每个专业,每种性别的学生数量,按照学生数量的降序显示结果
select tropt,count(tropt) from teacher group by tropt having count(tropt)>=5
对teacher表,显示职称和对应的认识,要求只有统计人数大于等于5人才显示

Multi-table query

Inner connection: The inner connection is matched according to the common columns of the two tables, and the two tables generally have a primary and foreign key relationship. Usually use the "=" comparison operator to determine whether the two columns of data are equal, by using the inner join keyword to associate between the tables
Make an internal connection to the sc and student tables, showing the student's student number, name, course number, and score.
语法1:
select student.sno,student.sname,sc.sno,sc.grage   from sc join student    on sc.sno=student.sno
语法2:
select student.sno,student.sname,sc.sno,sc.grage   from sc,student    where sc.sno=student.sno
Three tables connected
显示学生的学号,姓名,课程名,考试分数
语法1:
select student.sno,student.sname,course.cname,sc.grage   from sc join student   on sc.sno=student.sno   join course  on  sc.sno=course.sno
语法2:
select student.sno,student.sname,course.cname,sc.grage   from sc,student,course  where   sc.sno=student.sno  and  sc.sno=course.sno 
External connection: left join (left join), right join (right join), full outer join (full join)
Left outer connection
让student表和sc表进行左外连接,即不管是学生是否有选修课程,该学生的信息的都会显示出来
select student.sno,student.sname,sc.sno,sc.grade   from student left outer join sc  on student.sno=sc.sno
Right outer connection
让sc表和teacher表进行右外连接,显示教师编号,教师姓名,讲师教授的课程号
select teacher.tno,teacher.tname,sc.cno   from sc right outer join teacher  on sc.tno=teachaer.tno
Fully connected
让sc表和teacher表进行全外连接,显示教师编号,教师姓名,讲师教授的课程号。
teacher.tno,teacher.tname,sc.cno   from sc full outer join teacher   on sc.tno=teacher.tno 
Cross connection: there is no relationship between tables
让学生和课程两张表进行交叉连接
select *from student cross join course

Nested join

Subquery using in
过in引入的子查询结果是包含零个值或多个值得列表,子查询返回结果之后,外部查询将利用这些结果
Comparison operator modified with any, all
可以用all或者any修改引入子查询的比较运算符。some是与any等效的ISO标准,
以>比较运算符为例,>all表示大于每一个值,表示大于最大值。例如,>all(1,2,3)表示大于3
>any表示至少大于一个值,即大于最小值,因此>any(1,2,3)表示大于1
Use exists subquery
使用exists关键字引入子查询后,子查询的作用就相当于进行存在测试
外部查询的where子句测试子查询返回的行是否存在
子查询实际上不产生任何数据,它只返回TRUE或flase值

example

Equal to a single value to query the information of students who have a test score of 48 in a certain subject
select *from student   where sno=(select sno from sc where grade=48)
in list to query the information of students who have taken courses in the sc table
select *from student   where sno in (select distinct sno from sc) 
子查询得到学生的学号,外部查询根据学号找到学生
not in Query information about students who have not taken any courses
select * from student   where  sno not in (select distinct sno from sc)not in表示字段的值不在后面的子查询返回到结果中
In the teacher list, retrieve information about male teachers older than any female teacher
select *from teacher where tsex='男' and tage>all(select tage from teacher where tsex='女')子查询得到每一位女教师的年龄,外层查询使用“>all”的语法,即比集合中最大值还大
Query the basic information of students who have taken the B004 course
select *from student where exists (select *from sc where   sno=student.sno  and cno='B004')
Query the basic information of students who have not taken the X001 course
select *from student where not exists (select *from sc where   sno=student.sno  and cno='X001')
Query the basic information of all students studying in the same major as Kingdom
select sno,sname,smajor from student s1 where exists (select *from student s2 where s1.smajor=s2.smajor and s2.name='王国')

Collection query

And cross

Premise: The select statement must have the same number of columns

Parallel operation
将学生的学号,姓名,与教师的教工号,姓名,在一个检索结果中显示出来
select Sno,Sname from Student
union
select Tno,Tname from Teacher
//union       将多个查询结果合并起来时系统自动去掉重复元组
//union all   将多个查询结果合并起来时,保留重复元组
Crossover
对专业名以计算机开头的学生,及年龄为21的学生,用交运算求二者的交集
select Sno,Sname,Sage,Smajor from Student
where Smajor like'计算机%'
intersect
select Sno,Sname,Smajor from Student
where Sage=21
Difference operation
查询专业名以计算机开头的学生,但不包括年龄是21的学生
select Sno,Sname,Sage,Smajor from Student
where Smajor like '计算机%'
except
select Sno,Sname,Sage,Smajor from Student
where Sage=21

Data Update

Insert data

Insert a single row of data
Insert a row of data in the course, the four data are ('X004', 'Computer Frontier', 2, 'Elective')
insert into Course(Cno,Cname,Ccredit,XKLB)
values('X004','计算机前沿',2,'选修')
Insert subquery results
Extract the student number, name, and gender from the student table and insert it into the Teacher table. All newly inserted data are called lecturers.
insert into Teacher(Tno,Tname,Tsex)
select Sno,Sname,Ssex,'讲师' from Studnet

Query to create a new table

The information of the teacher's vocational school as a professor is stored in an expert table that does not yet exist
select * into experts from teacher
where Tprot='教授'

Update data, modify specific rows

Change the course number B002 in the course table to 3 credits
update course set ccredit=3
where cno='B002'
Modification with subquery
For the student table, use the existing professional field to store the number of the first course selected by the student
update student
set smajor
(select top 1 cno from sc where sc.sno=student.sno)

delete data

Delete rows that meet the conditions
Delete the record number B009 in the course table
delete from course
where cno='B009'
Delete with subquery
For the courses in the course table, no students have taken courses, delete operation
delete from course where cno not in
(select cno from sc)

view

Create view

Create a view called vwscs, which displays the student ID, name, gender, and major fields of the students in the computer department of the computer science department
create view vwscs
as
select sno,sname,ssex,tel,emall from student 
where sdept='计算机科学学院'

Update view

Update the data through the vwscs view, modify Yang Hua ’s phone to 13966667777
update vwscs
set tel='13966667777'
where sname='杨华'

Query view

select *from vwscore where score grade<85

index

Primary key index

Unique index

Clustered index clustered

Nonclustered index

Create and delete indexes

create index
drop index

Clustered index

alter table course2
add constraint pk_course2_cno primary key clustered(cno)

Unique index

create unique index idxcoursename
on course2(name)

Delete index

drop index idxcoursename on course2
drop index course2.idxcoursename

Guess you like

Origin www.cnblogs.com/dongxuelove/p/12739296.html