chapter-4-database statement

The following courses are derived from MOOC learning—see the original course: Database Principles and Applications
Postgraduate Review

overview

SQL Development

image-20210117214210476

Note: What functions are the keywords, especially the first create alter drop is to define functions

1. SQL is powerful, realizing data definition, data manipulation, data control and other functions

2. The SQL language is concise, and only a small number of verbs are used to realize the core functions

3. SQL supports the three-level schema structure of relational databases

4. SQL language can be embedded in programs written in other high-level languages

Note: statement format

image-20210117214252905 image-20210117214304490

Supplement: Mode create/drop schema <schema name> authorization <user name> Define schema = define namespace, you can further define database objects, etc.

Supplement: Index: create/drop [ unique/cluster ] index <index name> on <table name>(...column)

Basic table definition creation

#创建数据库
create database <数据库名>

#打开数据库
use <数据库名>

#创建表
create table <表名> (
 <属性名> <类型> [约束性条件],
 <属性名> <类型> [约束性条件]
)

#主键
sno char(6) primary key
#单独约束主键【多个外键时仅此一种方法】
primary key(sno,cno)

#外键
FOREIGN key(sno) references S(sno)

#后续添加外键级联操作--级联更新|不操作
# ON UPDATE{cascade| NO ACTION}:
# ON DELETE{cascade| NO action}:

#用户定义
SN CHAR(10) NOT NULL,

SEX CHAR(2) DEFALUT'男'
check(sex in('男','女'))

check(GRADE between 0 and 100)

SEX CHAR(2) UNIQUE



create table s(
sno VARCHAR(100) PRIMARY KEY,
sn VARCHAR(100),
sd VARCHAR(100),
sb VARCHAR(100),
sex VARCHAR(100) DEFAULT '男'
CHECK (sex in ('男','女'))
)

base table modification

增加列
alter table <表名>
 	add <属性名> <类型>
 	
#增加约束规则 	
alter table <表名>
	add  PRIMARY KEY (SNO);

#改变某列的类型
alter table <表名>
 	add column <属性名> <类型>
 	
#删除原有的列或者约束规则
alter table <表名> 
  drop column <列名> [CASCADE| RESTRICT]
 #RESTRICT没有视图或者约束引用该属性时,该属性列才可以删除
 #CASCADE删除某列时,对应的视图或者约束删除
 
alter table <表名>
  drop [constraint <约束条件>]
  
#删除表
drop table <表名>  [CASCADE| RESTRICT]

The query result shows select

The basics will not be repeated

1. In the SQL query statement, if all the attributes of a relational table need to be displayed in the result, use *

2. Remove duplicate tuple select distinct **** columns in the result [not removed by default]

3. Query result calculation [returned result]

  • Aggregate function: count/sum/avg/max/min [all|distinct] <columns>
  • For the null value of the attribute, it is not considered except count(), and count( ) only counts the number to be considered
  • Math Functions/String Functions/Date Functions

Example: select

Query results sort order by

select **
from ***
order by <目列> [ASC|DESC],<目标列> [ASC|DESC]

#ASC默认升序,降序DESC,如果第一目标列相同,按第二列排序
#<目列>也可以用1,2,3表示,表示第i列属性
#例如 order by 2,3 ASC

5. In the SQL query statement, how to rename the target column:

  • After renaming the object, use AS to indicate the new name , age as age1,
  • After renaming the object, add a new name with a space , age age1,
  • 【NOT】Indicate the new name in brackets after renaming

The query satisfies the condition like in

select .....
from ....
where <元组条件表达式>

Tuple condition expressions:

1. Operator: ± / % = > < and or not * For example: 5/3=1

**2. Predicate: [not] between ... and ... range [not] LIKE ... ** match

​[ not] IN (column name...) specified collection IS [not] NULL

image-20210117225758131
  1. where LIKE is used for partial match queries [ single quotes ]

where the string expression wildcard

_ represents any single character [can be 0 characters]

% means any long string whose length can be 0

<属性列名> [not] like 字符串表达式
where sn like '王%'
where cn like '%\ 实验' ESCAPE'\'  

#如果查询内容包括%,下划线,需要使用escape转换 

For example, if you search for DB_Design, then LIKE 'DB I_ Design' ESCAPE 'I'

​ Add an escape character in front, and add ESCAPE 'I' in the back

  1. Among them, IN is used to judge whether a value belongs to the collection
where sd in('数学','计算机')

Grouping aggregation group by, having

select .....
from ....
where <元组条件表达式>
group by <属性列名> [<属性列名>] [HAVING <选择条件>]

1. Group according to attribute name 1 and attribute name 2 values ​​in turn ; 2. having clause to filter the grouped results

#平均成绩90分以上 【不能用where是因为where不能用聚集函数avg
select sno,avg(grade)
from sc
where avg(grade)>=90 group by sno

#正确的写法
select sno,avg(grade)
from sc
group by sno having avg(grade)>90;

#男生人数>2人的系名
select sd
from sc
where sex="男"
group by sd having count(*)>2;

connection query join

Multi-table join query

#查询选修C01的学生姓名和成绩
select sn,grade
from sc,s  #sc和s做笛卡尔积运算
where sc.sno=s.sno and cno='c01'

Note that when connecting, you need to supplement the content equivalence relationship in where

Outer join query

from <left relation> left |right|full [outer] join <right relation> on <join condition>

#查询所有学生姓名及选修课程号为“C01”的成绩,没有选修该课程的学生,成绩显示为空
select sn,grade
from sc right outer join s
on sc.sno=s.sno and cno='c01'

[Normal/inner join] from <left relation> [inner] join <right relation> on <join condition>

#查询选修“数据结构”课程的学生的学号、姓名和成绩
select s.sno,sn,grade
from s,sc,c
where s.sno=sc.sno and c.cno=sc.cno and  cn='数据结构'

select s.sno,sn,grade
from (s inner join sc on s.sno=sc.sno) inner join c on c.cno=sc.cno
where cn='数据结构'

self join query

select ...
from s s1,s s2

from s as s1,s as s2

Example exercise: There are relations R(A, B, C) and S(C, D). The relational algebra expression equivalent to the SQL statement select A,B,D from R,S where RC=SC is ( ). πA,B,D(σR.C= SC(R×S))

Nested query method where in

Depending on whether the data processed in the subquery is related to the current tuple of the parent query,

Nested queries can be divided into independent subqueries and correlated subqueries

  1. Predicate IN [whether a value belongs to a set]

    image-20210117232440270
  2. comparison operator

    image-20210117232523444
  3. Quantifier ANY ALL [partially supported]

The semantics of ANY is a certain value in the query result. When a certain value in the subquery result satisfies the comparison operator , the comparison operation result is true.

The semantics of ALL are all values ​​in the query result. When each value in the subquery result satisfies the comparison operator , the comparison operation result is true.

image-20210117232718447 image-20210117232743279

Equivalence relationship [because any and all quantifiers are partially supported, so they can be replaced]

  1. Predicate exists [correlated subquery]

    Because the query condition (sc.sno) of the subquery needs to use the attribute (s.sno) of the parent query

#查询选修“C02”课程的学生姓名
SELECT SN
FROM S
WHERE SNO INSELECT SNO	FROM SC	WHERE CNO=‘C02’ )

SELECT SN
FROM S
WHERE EXISTSSELECT * FROM SC	WHERE SC.SNO=S.SNO AND CNO = ‘C02’)
#查询选修全部课程的学生的姓名
#选修全部课程的学生≡没有一门课他不选的学生
SELECT SN
FROM S
WHERE NOT EXISTS
(SELECT * FROM C
 WHERE NOT EXISTS
					(SELECT *  FROM SC
							WHERE SC.SNO=S.SNO AND				SC.CNO=C.CNO))

set operation

The select statement returns a collection, and multiple select statements can return multiple collections

In the two select statements participating in the collection query, the query results must not only have the same attribute name, but also the order of the attribute names must be consistent.

and union

#并
select [语句] union select [语句]


#查询选修了课程号为“C01”或“C02”的学生学号。
select sno from sc where cno='c01'
union 
select sno from sc where cno='c02'
#union自动去除重复项

select distinct sno from sc
where cno='c01' or cno='c02'

intersect

#交
select [语句] intersect select [语句]


#查询同时选修课程号为“C01”“C02”的学生学号。
select sno from sc where cno='c01'
intersect 
select sno from sc where cno='c02'

select  sno from sc
where cno='c01' and cno='c02'  #错误

select sno from sc
where cno='c01' and sno in (
  select sno from sc  where cno='c02'
)

difference except

#差
select [语句] except select [语句]


#查询选修了课程号为“C01”但没选修“C02”课程的学生学号
select sno from sc where cno='c01'
except 
select sno from sc where cno='c02'

select  sno from sc
where cno='c01' and cno='c02'  #错误
select sno from sc
where cno='c01' and sno not in (
  select sno from sc  where cno='c02'
)

Data Update

  1. insert tuple

**insert into <table name> (attribute name,…) value (value…) **Multiple tuples can be inserted

  • The constant value has the same value range and the same number as the corresponding attribute name.

  • If a certain attribute of the tuple does not appear after INTO, the values ​​on these attributes take the empty value NULL.

  • If no attributes are specified in INTO, the newly inserted tuple in the VALUES clause must have a value on each attribute , and the order of the constant values ​​must be consistent with the order of the attributes in the table definition.

  • The INSERT statement can insert data into the view

Example: INSERT INTO SC(SNO,CNO) VALUES ('S31','C01');

​ INSERT INTO S VALUES ('S31','Wang Hao','Computer','1999-10-15','Male');

Or the inserted tuple is the result of a subquery

Example: Insert the course selection record of the "Database" course for the students of the "Computer" department.

INSERT INTO SC(SNO,CNO)

​ SELECT SNO,CNO FROM S,C WHERE SD='Computer' AND CN='Database';

  1. Modify property value

update <table name> set <attribute>=<value> ,… where <condition> can modify multiple attribute values

  1. delete tuple

delete from <table name> [ where <condition> ]

Example: Delete course selection tuples whose grades are lower than the average grade of all courses

DELETE FROM SC WHERE GRADE<(SELECT AVG(GRADE) FROM SC);

  1. Sanity checks for update operations

The processing strategy adopted when the update operation cannot satisfy the referential integrity

Refuse to execute (NO ACTION) • Generate cascade operation (CASCADE) • Set to null value (SET NULL)

  1. The update operation does not change the schema structure of the relational table
  2. Updates are often based on queries, and updates may also nest subqueries
  3. Updates need to take into account various integrity constraints defined by the database

view

View (View) does not actually exist in the database, but a virtual table, row and column data from the table used in the query of the custom view, and is dynamically generated when the view is used.

That is, a view is the result set returned after executing a query statement, so when creating a view, the main thing is to create this SQL query statement.

For ordinary data tables, views have the following characteristics:

1. Simple: Because the view is the result set of compound conditions that have been filtered and returned after the execution of the query statement, users who use the view do not need to care about the structure, association conditions, and filter conditions of the subsequent corresponding tables.

2. Security: Users who use views can only access the result sets they are allowed to query. The authority management of tables cannot be limited to a certain row or column, but it can be easily realized through views.

3. Data independence: Once the structure of the view is determined, the impact of changes in the table structure on users can be shielded. Adding columns in the source table has no effect on the view; modifying the column name in the source table can be solved by modifying the view without causing damage to the view. Visitor Impact.

Second, the syntax of the view

create view <视图名> [列名,]
as  子查询
with check option 
#with check option 表示对视图进行和更新操作时,要满足视图定义的条件
#如果没有指明字段,默认所有字段

drop view <视图名> [cascade]

#正常的select,update语句

For ordinary data tables, views have the following characteristics:**

1. Simple: Because the view is the result set of compound conditions that have been filtered and returned after the execution of the query statement, users who use the view do not need to care about the structure, association conditions, and filter conditions of the subsequent corresponding tables.

2. Security: Users who use views can only access the result sets they are allowed to query. The authority management of tables cannot be limited to a certain row or column, but it can be easily realized through views.

3. Data independence: Once the structure of the view is determined, the impact of changes in the table structure on users can be shielded. Adding columns in the source table has no effect on the view; modifying the column name in the source table can be solved by modifying the view without causing damage to the view. Visitor Impact.

Second, the syntax of the view

create view <视图名> [列名,]
as  子查询
with check option 
#with check option 表示对视图进行和更新操作时,要满足视图定义的条件
#如果没有指明字段,默认所有字段

drop view <视图名> [cascade]

#正常的select,update语句

Guess you like

Origin blog.csdn.net/qq_38758371/article/details/130094064