2 2 SQ SQL语句基础
{课本第三章}
刘跃文 博士,副教授 西安交通大学管理学院 信息管理与电子商务系 liuyuewen@mail.xjtu.edu.cn V1, 2019-9-16
2 2 SQ SQL { } - - PowerPoint PPT Presentation
2 2 SQ SQL { } liuyuewen@mail.xjtu.edu.cn V1, 2019-9-16 Outline 1.
{课本第三章}
刘跃文 博士,副教授 西安交通大学管理学院 信息管理与电子商务系 liuyuewen@mail.xjtu.edu.cn V1, 2019-9-16
创建表、主键约束、外键约束
简单查询、连接查询、聚合查询、嵌套查询
增、删、改
2
IBM顺序语言,之后重命名为 Structured Query Language (SQL, 结构化查询语言,读作sikəu)
加上其它一些标准中的语句,以及一些特有的语句
create table r (A1 D1, A2 D2, ..., An Dn, (integrity-constraint1), ..., (integrity-constraintk))
5
create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2))
6
ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department)
7
8
maximum length n.
domain type).
digits, with n digits to the right of decimal point.
point numbers, with machine-dependent precision.
least n digits.
类型说明 取值范围 tinyint[(m)] 有符号值:–128到127(–2^7到2^7–1) 无符号值:0到255(0到2^8–1) smallint[(m)] 有符号值:–32768到32767(–2^15到2^15–1) 无符号值:0到65535(0到2^16–1) int[(m)] 有符号值:–2147683648到2147683647(–2^31到2^31–1) 无符号值:0到4294967295(0到2^32–1) bigint[(m)] 有符号值:–9223372036854775808到 9223373036854775807(–2^63到2^63–1) 无符号值:0到18446744073709551615(0到2^64–1) float 最小非零值:±1.175494351e–38 double 最小非零值:±2.2250738585072014e–308 decimal(m,d) 可变;其值的范围依赖于m和d
ensures not null 主键自动不为null
13
unique tuple of each possible relation r(R)
Example: {ID} is a candidate key for Instructor
another
14
身份证号 学号 姓名 性别 生辰 学院 GPA
15
学院名称 院长 院址
Example: Declare dept_name as the primary key for department
create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department)
16
ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department);
17
ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year), foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section );
18
course_id varchar(8), prereq_id varchar(8), primary key (course_id, prereq_id), foreign key (course_id) references course, foreign key (prereq_id) references course);
19
primary key);
the FTable?
the PTable?
PTable; (2) you missed attributes in the foreign key table.
foreign key set in the FTable?
the PTable?
primary key to be a foreign key; (3) the primary key is combined by several sets of foreign keys.
PTable?
Section表的主键是(Couse_ID, Sec_ID, Semester, Year)如果Section表有一个 Section_ID,能唯一代表一个Section,从而成为Section表的主键,那么只需 要一个外键,Section_ID即可。
中的外键顺序(如sName, sID)不同时,使用括号标注对应关系
course_id varchar(8) primary key, title varchar(50), dept_name varchar(20), credits numeric(2,0), foreign key (dept_name) references department);
declaration as shown above
primary key (course_id)
user_ID varchar(50), user_name varchar(50), homepage_url varchar(500), primary key (user_ID))
user_ID varchar(50), friend_ID varchar(50), primary key (user_ID,friend_ID), foreign key (user_ID) references user, foreign key (friend_ID) references user)
26
article_ID varchar(50), content varchar(max), author_ID varchar(50), primary key (article_ID), foreign key (author_ID) references user)
user_ID varchar(50), article_ID varchar(50), repost_time datetime, primary key (user_ID,article_ID), foreign key (user_ID) references user, foreign key (article_ID) references article)
27
28
1 建表的顺序是什么? 2 可以直接删除course表吗? 3 插入数据的顺序是什么? 4 可以直接删除student表中的一行数据吗?
29
30
31
and D is the domain of A.
new attribute.
references department
(school_name), constraint fk_school_dean foreign key (dean) references instructor (ID);
drop constraint pk_schook, fk_school_dean
Create database dbname on (name='dbname_data',filename=‘D:\dbn ame.mdf',size=50MB,filegrowth=10%) log on (name='dbname_log', filename=‘D:\dbname.log', size=50MB, maxsize=100MB, filegrowth=1MB)
36
3.3 Basic Query Structure 基本查询结构[掌握]
provides the ability to query information, and insert, delete and update tuples 元组:一行数据
select A1, A2, ..., An from r1, r2, ..., rm where P
系代数
变换、重命名各个属性,从而形成一个自己想要的属性列表。
select name from instructor
use upper- or lower-case letters.)
保留字自动变色]
after select.
duplicates select distinct dept_name from instructor
select all dept_name from instructor
select * from instructor
tuples.
select ID, name, salary/12 from instructor would return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12.
algebra.
select name from instructor where dept_name = 'Comp. Sci.' and salary > 80000
and, or, and not.
术表达式.
relational algebra.
select from instructor, teaches
attributes from both relations
where-clause condition (selection operation in relational algebra)
instructor teaches
the course ID of the courses they taught. select name, course_id from instructor, teaches where instructor.ID = teaches.ID
the Comp. Sci. department select section.course_id, semester, year, title from section, course where section.course_id = course.course_id and dept_name = ‘Comp. Sci.'
并方法是:对于A中的每一行,匹配B中的每一行。所以,假设A 是m行,B是n行,就形成了一个mn行的表,也就是笛卡尔积。
“A.id=B.id”的数据,这样结果表的数据量一下就降下来。
那么在执行结果中,id=1的表仍然会有6条。
45
id S_id 1 a 1 b 1 c id Course 1 Calculus 1 CS 2 DB
筛选出来,那么这个条件未必就必须是“=”的条件。
录,匹配所有比其Score高的B的记录。
46
id Score 1 100 2 60 3 80 id Score 1 75 2 90 3 40
id Scor e id Score 2 60 1 75 2 60 2 90 3 80 2 90
列A,B表的所有字段。但是这些字段名是可以自己指定的。
那么可以直接写字段名;如果字段名不唯一,必须写A.name或 者B.name,否则会报错。
47
attributes, and retains only one copy of each common column [看起 来省事的办法]
from instructor natural join teaches;
from instructor
some instructor in ‘Comp. Sci’.
from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’
instructor as T ≡ instructor T
能使用。一些错误的用法如下:
atten_Score, exam_Score+atten_Score as final_score from stuPerformance
where exam_Score>70
52
举两个例子:
53
id fid 1 2 2 4 3 1
id fid 1 2 2 4 3 1
id fid ffid 1 2 4 3 1 2
顺序),Ptime(交易时间)
A.PosID=B.PosID and A.Seq=B.Seq+1 and DateDiff(Minute,A.Ptime,B.Ptime)<=3
54
PosI D CusI D Seq PTim e 1 a 1 3:02 1 b 2 3:03 1 c 3 3:05 PosI D CusID Seq PTime BID 1 b 2 3:03 a 1 c 3 3:05 b PosI D CusI D Seq PTim e 1 a 1 3:02 1 b 2 3:03 1 c 3 3:05
special characters:
“dar”.
select name from instructor where name like '%dar%'
like ‘100 \%' escape 转义字符 '\'
连接字符在SQL Server中可以用+,用||会报错。
ltrim(), rtrim(), substring(), charindex()
只会返回第一条数据 因为这里’%’被当做普通字符串
只会返回全部5条数据 因为这里’%’被当做通配符
57
select distinct name from instructor
and $100,000 (that is, $90,000 and $100,000)
from instructor where salary between 90000 and 100000
from instructor, teaches where (instructor.ID, dept_name) = (teaches.ID, ’Biology’);
union select course_id from section where sem = ‘Spring’ and year = 2010
intersect select course_id from section where sem = ‘Spring’ and year = 2010
except select course_id from section where sem = ‘Spring’ and year = 2010
60
61
Union Intersect Except
duplicates
union all, intersect all and except all. Suppose a tuple occurs m times in r and n times in s, then, it
表中的数据进行去重,再进行集合运算。
63
union/union all/intersect/except select name from B
64
some of their attributes
select name from instructor where salary is null
(unknown or false) = unknown (unknown or unknown) = unknown
(false and unknown) = false, (unknown and unknown) = unknown
unknown
unknown
Unknown
67
column of a relation, and return a value
avg: average value min: minimum value max: maximum value sum: sum of values count: number of values
department
from instructor where dept_name= ’Comp. Sci.’;
Spring 2010 semester
from teaches where semester = ’Spring’ and year = 2010
from course;
from instructor group by dept_name;
appear in group by list
select dept_name, ID, avg (salary) from instructor group by dept_name;
72
Good_ID Good_Name Good_Price 1 iPhone 5000.00 2 SamSung 2000.00 3 Leshi 1000.00 4 Huawei 3000.00
average salary is greater than 42000 select dept_name, avg (salary) from instructor group by dept_name having avg (salary) > 42000;
formation of groups whereas predicates in the where clause are applied before forming groups
select dept_name, avg (salary) from instructor where salary > 42000 group by dept_name
73
select sum (salary ) from instructor
values on the aggregated attributes [null会被忽略]
another query.
set comparisons, and set cardinality.
select distinct course_id from section where semester = ’Fall’ and year= 2009 and course_id in (select course_id from section where semester = ’Spring’ and year= 2010);
select distinct course_id from section where semester = ’Fall’ and year= 2009 and course_id not in (select course_id from section where semester = ’Spring’ and year= 2010);
76
sections taught by the instructor with ID 10101
select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teaches where teaches.ID= 10101);
77
least one) instructor in the Biology department. select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = ’Biology’;
select name from instructor where salary > some (select salary from instructor where dept_name = ’Biology’);
78
Where <comp> can be:
79
salary of all instructors in the Biology department. select name from instructor where salary > all (select salary from instructor where dept_name = ’Biology’);
80
81
is nonempty.
both the Fall 2009 semester and in the Spring 2010 semester” select course_id from section as S where semester = ’Fall’ and year= 2009 and exists (select * from section as T where semester = ’Spring’ and year= 2010 and S.course_id= T.course_id);
salary is greater than $42,000. select dept_name, avg_salary from (select dept_name, avg (salary) as avg_salary from instructor group by dept_name) as tb where avg_salary > 42000;
select dept_name, avg_salary from (select dept_name, avg (salary) from instructor group by dept_name) as dept_avg (dept_name, avg_salary) where avg_salary > 42000;
whose definition is available only to the query in which the with clause occurs.
with max_budget (value) as (select max(budget) from department) select budget from department, max_budget where department.budget = max_budget.value;
the total salary at all departments with dept _total (dept_name, value) as (select dept_name, sum(salary) from instructor group by dept_name), dept_total_avg(value) as (select avg(value) from dept_total) select dept_name from dept_total, dept_total_avg where dept_total.value >= dept_total_avg.value;
86
(select count(*) from instructor where department.dept_name = instructor.dept_name) as num_instructors from department;
from instructor where salary * 10 > (select budget from department where department.dept_name = instructor.dept_name)
from goods
88
delete from instructor
delete from instructor where dept_name = ’Finance’;
associated with a department located in the Watson building. delete from instructor where dept_name in (select dept_name from department where building = ’Watson’);
instructors delete from instructor where salary < (select avg (salary) from instructor);
changes
avg or retesting the tuples)
92
Modification of the Database – Insertion 插入 [掌握]
insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
insert into course (course_id, title, dept_name, credits) values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
insert into student values (’3003’, ’Green’, ’Finance’, null);
Insertion (Cont.) [掌握]
insert into student select ID, name, dept_name, 0 from instructor
results are inserted into the relation (otherwise queries like insert into table1 select * from table1 would cause problems, if table1 did not have any primary key defined.
insert into student(ID,name) select ID,name from instructor
id,name,dept_name,salary*12,0 from sourceTB where dept_name=‘CompSci’
95
and all others receive a 5% raise
update instructor set salary = salary * 1.03 where salary > 100000; update instructor set salary = salary * 1.05 where salary <= 100000;
update instructor set salary = case when salary <= 100000 then salary * 1.05 else salary * 1.03 end
select case when salary <= 100000 then salary * 1.05 else salary * 1.03 end from instructor
score>=70 then ‘C’ when score>=60 then ‘D’ else ‘F’ end
98
A.id=B.id
99
组外键references同一个表),建表、删表、插入数据、删除数 据的次序
100
101
liuyuewen@xjtu.edu.cn
102