《数据库原理PPT课件第三章.ppt》由会员分享,可在线阅读,更多相关《数据库原理PPT课件第三章.ppt(294页珍藏版)》请在三一办公上搜索。
1、Chapter 3: SQL,Chapter 3: SQL,Data DefinitionBasic Query StructureSet OperationsAggregate FunctionsNull ValuesNested SubqueriesComplex Queries ViewsModification of the DatabaseJoined Relations*,3.1 History,IBM Sequel language developed as part of System R project at the IBM San Jose Research Laborat
2、oryRenamed Structured Query Language (SQL)ANSI and ISO standard SQL:SQL-86SQL-89SQL-92 SQL:1999 (language name became Y2K compliant!)SQL:2003Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features. Not all examples h
3、ere may work on your particular system.,3.2 Data Definition Language,The schema for each relation.The domain of values associated with each attribute.Integrity constraintsThe set of indices to be maintained for each relations.Security and authorization information for each relation.The physical stor
4、age structure of each relation on disk.,Allows the specification of not only a set of relations but also information about each relation, including:,1.Domain Types in SQL,char(n). Fixed length character string, with user-specified length n.varchar(n). Variable length character strings, with user-spe
5、cified maximum length n. Nchar(n), nVarchar(n) (for unicode ,2byte code,1-4000 chars)Text. Variable length character strings,1 to 2GB.=varchar(max)int. Integer (4B,a finite subset of the integers that is machine-dependent).smallint. Small integer (2B,a subset of the integer domain type).Bigint. Big
6、integer (8B),tinyint(1B),bit(多个位占1B)numeric(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. Decimal(p,d).,1.Domain Types in SQL(cnt),real, double precision. Floating point and double-precision floating point numbers, with machine-depe
7、ndent precision.float(n). Floating point number, with user-specified precision of at least n digits.Datatime 8B:yyyy.mm.dd h:m:s,smalldatatime 4BMoney 8BXml (2GB)(不同表单可以存在xml类型的属性字段中)Binary(n) 1-8000BImage 2GBTimestamp 8BSql_variant 8016bit,可存储除text、image、timestamp、sql-variantCursor:查询结果的数据集Table:表格
8、式数据,2.Create database/tabale,CREATE DATABASE database_nameON PRIMARY(NAME = student_data FILENAME = C:Program FilesMicrosoft erverMSSQL.1MSSQLDatastudent.mdf, SIZE = 10MB, MAXSIZE = 50MB, FILEGROWTH = 10%),- FILEGROWTH = 10%LOG ON( NAME = student_log, FILENAME = C:Program FilesMicrosoft SQL ServerMS
9、SQL.1 MSSQL Data student.ldf, SIZE = 1MB, MAXSIZE =20MB, FILEGROWTH = 10%),Create Table Construct,An SQL relation is defined using the create table command:create table r (A1 D1, A2 D2, ., An Dn,(integrity-constraint1),.,(integrity-constraintk)r is the name of the relationeach Ai is an attribute nam
10、e in the schema of relation rDi is the data type of values in the domain of attribute AiExample:create table branch(branch_name char(15) not null, branch_city char(30), assetsinteger),Database schama,Integrity Constraints in Create Table,not nullprimary key (A1, ., An ),Example: Declare branch_name
11、as the primary key for branch.create table branch (branch_namechar(15), branch_citychar(30), assetsinteger, primary key (branch_name) ),primary key declaration on an attribute automatically ensures not null in SQL-92 onwards, needs to be explicitly stated in SQL-89,create table c_s(student_idchar(8)
12、,course_nochar(4),gradeinteger,primary key(student_id, course_no),foreign key(student_id) references student(id),foreign key(course_no) references course(course_no);,名字可以不同域必须相同,3.Drop and Alter Table Constructs,The drop table command deletes all information about the dropped relation from the datab
13、ase.The alter table command is used to add / drop attributes to an existing relation: alter table r add A D where A is the name of the attribute to be added to relation r and D is the domain of A.All tuples in the relation are assigned null as the value for the new attribute. alter table r drop A al
14、ter table sc alter column sno char(4); where A is the name of an attribute of relation r drop table r drop database studentDropping of attributes not supported by many databases,3.3 Basic Query Structure,SQL is based on set and relational operations with certain modifications and enhancementsA typic
15、al SQL query has the form:select A1, A2, ., Anfrom r1, r2, ., rmwhere PAi represents an attributeRi represents a relationP is a predicate.This query is equivalent to the relational algebra expression.The result of an SQL query is a relation.,3.3.1.The select Clause,The select clause list the attribu
16、tes desired in the result of a querycorresponds to the projection operation of the relational algebraExample: find the names of all branches in the loan relation:select branch_namefrom loanIn the relational algebra, the query would be: branch_name (loan)NOTE: SQL names are case insensitive (i.e., yo
17、u may use upper- or lower-case letters.) E.g. Branch_Name BRANCH_NAME branch_nameSome people use upper case wherever we use bold font.,The select Clause (Cont.),SQL allows duplicates in relations as well as in query results.To force the elimination of duplicates, insert the keyword distinct after se
18、lect.Find the names of all branches in the loan relations, and remove duplicatesselect distinct branch_namefrom loanThe keyword all specifies that duplicates not be removed. select all branch_namefrom loan,The select Clause (Cont.),An asterisk in the select clause denotes “all attributes”select *fro
19、m loanThe select clause can contain arithmetic expressions involving the operation, +, , , and /, and operating on constants or attributes of tuples.The query: select loan_number, branch_name, amount 100 from loanwould return a relation that is the same as the loan relation, except that the value of
20、 the attribute amount is multiplied by 100.,2.The where Clause,The where clause specifies conditions that the result must satisfyCorresponds to the selection predicate of the relational algebra. To find all loan number for loans made at the Perryridge branch with loan amounts greater than $1200.sele
21、ct loan_numberfrom loanwhere branch_name = Perryridge and amount 1200Comparison results can be combined using the logical connectives and, or, and not. Comparisons can be applied to results of arithmetic expressions.,The where Clause (Cont.),SQL includes a between comparison operatorExample: Find th
22、e loan number of those loans with loan amounts between $90,000 and $100,000 (that is, $90,000 and $100,000),select loan_numberfrom loanwhere amount between 90000 and 100000 OR: where amount =90000 and amount =100000,3.The from Clause,The from clause lists the relations involved in the queryCorrespon
23、ds to the Cartesian product operation of the relational algebra.Find the Cartesian product borrower X loanselect from borrower, loan,Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch.,select customer_name, borrower.loan_number, amount from borrower, l
24、oan where borrower.loan_number = loan.loan_number and branch_name = Perryridge,4.The Rename Operation,The SQL allows renaming relations and attributes using the as clause:old-name as new-nameFind the name, loan number and loan amount of all customers; rename the column name loan_number as loan_id.,s
25、elect customer_name, borrower.loan_number as loan_id, amountfrom borrower, loanwhere borrower.loan_number = loan.loan_number,5.Tuple Variables,Tuple variables are defined in the from clause via the use of the as clause.Find the customer names and their loan numbers for all customers having a loan at
26、 some branch.,Find the names of all branches that have greater assets than some branch located in Brooklyn. select distinct T.branch_name from branch as T, branch as S where T.assets S.assets and S.branch_city = Brooklyn Keyword as is optional and may be omitted borrower as T borrower T,select custo
27、mer_name, T.loan_number, S.amount from borrower as T, loan as S where T.loan_number = S.loan_number,6.String Operations,SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters:percent (%). The % c
28、haracter matches any substring.underscore (_). The _ character matches any character.Find the names of all customers whose street includes the substring “Main”.select customer_namefrom customerwhere customer_street like % Main% Match the name “Main%”like Main% escape SQL supports a variety of string
29、 operations such asconcatenation (using “|”) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.,Ordering the Display of Tuples,List in alphabetic order the names of all customers having a loan in Perryridge branchselect distinct customer_namefrom
30、borrower, loanwhere borrower loan_number = loan.loan_number and branch_name = Perryridge order by customer_name ascWe may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default.Example: order by customer_name desc,Duplicates,In relations with
31、 duplicates, SQL can define how many copies of tuples appear in the result.Multiset versions of some of the relational algebra operators given multiset relations r1 and r2:1. (r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies selections , then there are c1 copies of t1 in (r1).2. A (r
32、): For each copy of tuple t1 in r1, there is a copy of tuple A (t1) in A (r1) where A (t1) denotes the projection of the single tuple t1.3. r1 x r2 : If there are c1 copies of tuple t1 in r1 and c2 copies of tuple t2 in r2, there are c1 x c2 copies of the tuple t1. t2 in r1 x r2,Duplicates (Cont.),E
33、xample: Suppose multiset relations r1 (A, B) and r2 (C) are as follows: r1 = (1, a) (2,a) r2 = (2), (3), (3)Then B(r1) would be (a), (a), while B(r1) x r2 would be(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)SQL duplicate semantics: select A1, A2, ., Anfrom r1, r2, ., rmwhere Pis equivalent to the multis
34、et version of the expression:,3.3.2 Set Operations,The set operations union, intersect, and except operate on relations and correspond to the relational algebra operations Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multiset versio
35、ns union all, intersect all and except all.Suppose a tuple occurs m times in r and n times in s, then, it occurs:m + n times in r union all smin(m,n) times in r intersect all smax(0, m n) times in r except all s,Set Operations,Find all customers who have a loan, an account, or both:,(select customer
36、_name from depositor)except(select customer_name from borrower),(select customer_name from depositor)intersect(select customer_name from borrower),Find all customers who have an account but no loan.,(select customer_name from depositor)union(select customer_name from borrower),Find all customers who
37、 have both a loan and an account.,3.3.3 Aggregate Functions,These functions operate on the multiset of values of a column of a relation, and return a valueavg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of values,Aggregate Functions (Cont.),Find the average acco
38、unt balance at the Perryridge branch.,Find the number of depositors in the bank.,Find the number of tuples in the customer relation.,select avg (balance)from accountwhere branch_name = Perryridge,select count (*)from customer,select count (distinct customer_name)from depositor,select avg (distinct b
39、alance) ,Aggregate Functions Group By,Find the number of depositors for each branch.,Note: Attributes in select clause outside of aggregate functions must appear in group by list(除聚集函数外,在select中出现的属性必须在group by中出现)(Group by branch_name,street -先按branch_name分组,在组内再按street分组),select branch_name, count
40、 (distinct customer_name)from depositor, accountwhere depositor.account_number = account.account_numbergroup by branch_name,Aggregate Functions Having Clause,Find the names of all branches where the average account balance is more than $1,200.,Note: predicates in the having clause are applied after
41、the formation of groups whereas predicates in the where clause are applied before forming groups(where 条件作用于 分组前,而having条件作用于分组后,即每组满足的条件),select branch_name, avg (balance) from account group by branch_name having avg (balance) 1200,使用GROUP BY子句可以按一定的条件对查询到的结果进行分组,再对每一组数据计算统计信息。 SELECT column_name1,
42、 column_name2 ,.n FROM table_name WHERE search_condition GROUP BY group_by_expression HAVING search_condition GROUP BY将查询结果按 (group_by_expression)进行分组,该属性列相等的记录为一个组。 通常,在每组中通过聚合函数来计算一个或者多个列。 如果GROUP带有HAVING,则只有满足search_condition的组才能输出。,GROUP BY与HAVING子句,The Complete SELECT Statement,SELECT attribute
43、 list - Output columns of result table FROM table list - Input tables WHERE selection-condition - Condition to filter out rows GROUP BY grouping attribute(s) - Grouping of rows with common - column values HAVING grouping condition - Condition to filter out groups ORDER BY attribute ASC|DESCpairs - O
44、rdering of rows in output (order by branch_name,assets -先按b_n排序,b_n相等的再按assets排)Notes: Only the first two are mandatory; the rest are optional The order of the clauses cannot be changed. Optional clauses can be omitted. FROM 最多可以指定16个表,Null Values,It is possible for tuples to have a null value, deno
45、ted by null, for some of their attributesnull signifies an unknown value or that a value does not exist.The predicate is null can be used to check for null values.Example: Find all loan number which appear in the loan relation with null values for amount.select loan_numberfrom loanwhere amount is nu
46、llThe result of any arithmetic expression involving null is nullExample: 5 + null returns nullHowever, aggregate functions simply ignore nullsMore on next slide,Null Values and Three Valued Logic,Any comparison with null returns unknownExample: 5 null or null = nullThree-valued logic using the truth
47、 value unknown:OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknownAND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknownNOT: (not unknown) = unknown“P is unknown” evaluates to true if predicate P evaluates to unknownResul
48、t of where clause predicate is treated as false if it evaluates to unknown,Null Values and Aggregates,Total all loan amountsselect sum (amount )from loanAbove statement ignores null amountsResult is null if there is no non-null amountAll aggregate operations except count(*) ignore tuples with null v
49、alues on the aggregated attributes.,Null Values and Aggregates,例:统计有成绩的学生的人数 SELECT COUNT (SCORE) FROM SC -成绩为零的同学计算,没有成绩(即为空值)的不计,SELECT COUNT(*) FROM S WHERE DEPT=计算机注意:COUNT(*)用来统计元组的个数。此函数不消除重复行,也不允许使用DISTINCT关键字,Nested Subqueries,SQL provides a mechanism for the nesting of subqueries.A subquery
50、 is a select-from-where expression that is nested within another query.A common use of subqueries is to perform tests for set membership, set comparisons, and set cardinality.,Example Query,Find all customers who have both an account and a loan at the bank.,Find all customers who have a loan at the