山大數(shù)據(jù)庫系統(tǒng)英語課件04中級SQL_第1頁
山大數(shù)據(jù)庫系統(tǒng)英語課件04中級SQL_第2頁
山大數(shù)據(jù)庫系統(tǒng)英語課件04中級SQL_第3頁
山大數(shù)據(jù)庫系統(tǒng)英語課件04中級SQL_第4頁
山大數(shù)據(jù)庫系統(tǒng)英語課件04中級SQL_第5頁
已閱讀5頁,還剩47頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、Chapter 4: Intermediate SQLChapter 4: Intermediate SQLJoin ExpressionsViewsTransactionsIntegrity ConstraintsSQL Data Types and SchemasAuthorizationJoined RelationsJoin operations take two relations and return as a result another relation.A join operation is a Cartesian product which requires that tu

2、ples in the two relations match (under some condition). It also specifies the attributes that are present in the result of the join The join operations are typically used as subquery expressions in the from clauseJoin operations ExampleRelation courseRelation prereq Observe that prereq information i

3、s missing for CS-315 and course information is missing for CS-437Outer JoinAn extension of the join operation that avoids loss of information.Computes the join and then adds tuples form one relation that does not match tuples in the other relation to the result of the join. Uses null values.Left Out

4、er Join course natural left outer join prereqRight Outer Join course natural right outer join prereqJoined RelationsJoin operations take two relations and return as a result another relation.These additional operations are typically used as subquery expressions in the from clauseJoin condition defin

5、es which tuples in the two relations match, and what attributes are present in the result of the join.Join type defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.Full Outer Join course natural full outer join prereqJoined

6、Relations Examples course inner join prereq oncourse.course_id = prereq.course_idWhat is the difference between the above, and a natural join? course left outer join prereq oncourse.course_id = prereq.course_idJoined Relations Examplescourse natural right outer join prereq course full outer join pre

7、req using (course_id)ViewsIn some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.)Consider a person who needs to know an instructors name and department, but not the salary. This person should see a relation describe

8、d, in SQL, by select ID, name, dept_name from instructorA view provides a mechanism to hide certain data from the view of certain users. Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.View DefinitionA view is defined using the

9、create view statement which has the formcreate view v as where is any legal SQL expression. The view name is represented by v.Once a view is defined, the view name can be used to refer to the virtual relation that the view generates.View definition is not the same as creating a new relation by evalu

10、ating the query expression Rather, a view definition causes the saving of an expression; the expression is substituted into queries using the view.Example ViewsA view of instructors without their salary create view faculty as select ID, name, dept_name from instructorFind all instructors in the Biol

11、ogy department select name from faculty where dept_name = BiologyCreate a view of department salary totals create view departments_total_salary(dept_name, total_salary) as select dept_name, sum (salary) from instructor group by dept_name;Views Defined Using Other Viewscreate view physics_fall_2009 a

12、s select course.course_id, sec_id, building, room_number from course, section where course.course_id = section.course_id and course.dept_name = Physics and section.semester = Fall and section.year = 2009;create view physics_fall_2009_watson as select course_id, room_number from physics_fall_2009 whe

13、re building= Watson;View ExpansionExpand use of a view in a query/another viewcreate view physics_fall_2009_watson as(select course_id, room_numberfrom (select course.course_id, building, room_number from course, section where course.course_id = section.course_id and course.dept_name = Physics and s

14、ection.semester = Fall and section.year = 2009)where building= Watson;Views Defined Using Other ViewsOne view may be used in the expression defining another view A view relation v1 is said to depend directly on a view relation v2 if v2 is used in the expression defining v1A view relation v1 is said

15、to depend on view relation v2 if either v1 depends directly to v2 or there is a path of dependencies from v1 to v2 A view relation v is said to be recursive if it depends on itself.View ExpansionA way to define the meaning of views defined in terms of other views.Let view v1 be defined by an express

16、ion e1 that may itself contain uses of view relations.View expansion of an expression repeats the following replacement step:repeatFind any view relation vi in e1Replace the view relation vi by the expression defining vi until no more view relations are present in e1As long as the view definitions a

17、re not recursive, this loop will terminateUpdate of a ViewAdd a new tuple to faculty view which we defined earlierinsert into faculty values (30765, Green, Music);This insertion must be represented by the insertion of the tuple(30765, Green, Music, null)into the instructor relationSome Updates canno

18、t be Translated Uniquely create view instructor_info as select ID, name, building from instructor, department where instructor.dept_name= department.dept_name;insert into instructor_info values (69987, White, Taylor);which department, if multiple departments in Taylor?what if no department is in Tay

19、lor?Most SQL implementations allow updates only on simple views The from clause has only one database relation.The select clause contains only attribute names of the relation, and does not have any expressions, aggregates, or distinct specification.Any attribute not listed in the select clause can b

20、e set to nullThe query does not have a group by or having clause.And Some Not at Allcreate view history_instructors as select * from instructor where dept_name= History;What happens if we insert (25566, Brown, Biology, 100000) into history_instructors?Materialized ViewsMaterializing a view: create a

21、 physical table containing all the tuples in the result of the query defining the viewIf relations used in the query are updated, the materialized view result becomes out of dateNeed to maintain the view, by updating the view whenever the underlying relations are updated.TransactionsUnit of workAtom

22、ic transactioneither fully executed or rolled back as if it never occurredIsolation from concurrent transactionsTransactions begin implicitlyEnded by commit work or rollback workBut default on most databases: each SQL statement commits automaticallyCan turn off auto commit for a session (e.g. using

23、API)In SQL:1999, can use: begin atomic . endNot supported on most databasesIntegrity ConstraintsIntegrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency. A checking account must have a balan

24、ce greater than $10,000.00A salary of a bank employee must be at least $4.00 an hourA customer must have a (non-null) phone number Integrity Constraints on a Single Relation not nullprimary keyuniquecheck (P), where P is a predicateNot Null and Unique Constraints not nullDeclare name and budget to b

25、e not null name varchar(20) not null budget numeric(12,2) not nullunique ( A1, A2, , Am)The unique specification states that the attributes A1, A2, Amform a candidate key.Candidate keys are permitted to be null (in contrast to primary keys).The check clausecheck (P) where P is a predicateExample: en

26、sure that semester is one of fall, winter, spring or summer:create table section ( course_id varchar (8), sec_id varchar (8), semester varchar (6), year numeric (4,0), building varchar (15), room_number varchar (7), time slot id varchar (4), primary key (course_id, sec_id, semester, year), check (se

27、mester in (Fall, Winter, Spring, Summer);Referential IntegrityEnsures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation.Example: If “Biology” is a department name appearing in one of the tuples in the instructor r

28、elation, then there exists a tuple in the department relation for “Biology”.Let A be a set of attributes. Let R and S be two relations that contain attributes A and where A is the primary key of S. A is said to be a foreign key of R if for any values of A appearing in R these values also appear in S

29、.Cascading Actions in Referential Integritycreate table course ( course_id char(5) primary key, title varchar(20), dept_name varchar(20) references department)create table course ( dept_name varchar(20), foreign key (dept_name) references department on delete cascade on update cascade, . . . )altern

30、ative actions to cascade: set null, set defaultIntegrity Constraint Violation During TransactionsE.g.create table person (ID char(10),name char(40),mother char(10),father char(10),primary key ID,foreign key father references person,foreign key mother references person)How to insert a tuple without c

31、ausing constraint violation ?insert father and mother of a person before inserting personOR, set father and mother to null initially, update after inserting all persons (not possible if father and mother attributes declared to be not null) OR defer constraint checking (next slide)Complex Check Claus

32、escheck (time_slot_id in (select time_slot_id from time_slot)why not use a foreign key here?Every section has at least one instructor teaching the section.how to write this?Unfortunately: subquery in check clause not supported by pretty much any databaseAlternative: triggers (later)create assertion

33、check ;Also not supported by anyoneBuilt-in Data Types in SQL date: Dates, containing a (4 digit) year, month and dateExample: date 2005-7-27time: Time of day, in hours, minutes and seconds.Example: time 09:00:30 time 09:00:30.75timestamp: date plus time of dayExample: timestamp 2005-7-27 09:00:30.7

34、5interval: period of timeExample: interval 1 daySubtracting a date/time/timestamp value from another gives an interval valueInterval values can be added to date/time/timestamp valuesIndex Creationcreate table student(ID varchar (5),name varchar (20) not null,dept_name varchar (20),tot_cred numeric (

35、3,0) default 0,primary key (ID)create index studentID_index on student(ID)Indices are data structures used to speed up access to records with specified values for index attributese.g. select * from student where ID = 12345can be executed by using the index to find the required record, without lookin

36、g at all records of studentMore on indices in Chapter 11User-Defined Typescreate type construct in SQL creates user-defined typecreate type Dollars as numeric (12,2) final create table department(dept_name varchar (20),building varchar (15),budget Dollars);Domainscreate domain construct in SQL-92 cr

37、eates user-defined domain typescreate domain person_name char(20) not nullTypes and domains are similar. Domains can have constraints, such as not null, specified on them.create domain degree_level varchar(10)constraint degree_level_testcheck (value in (Bachelors, Masters, Doctorate);Large-Object Ty

38、pesLarge objects (photos, videos, CAD files, etc.) are stored as a large object:blob: binary large object - object is a large collection of uninterpreted binary data (whose interpretation is left to an application outside of the database system)clob: character large object - object is a large collec

39、tion of character dataWhen a query returns a large object, a pointer is returned rather than the large object itself.AuthorizationForms of authorization on parts of the database:Read - allows reading, but not modification of data.Insert - allows insertion of new data, but not modification of existin

40、g data.Update - allows modification, but not deletion of data.Delete - allows deletion of data.Forms of authorization to modify the database schemaIndex - allows creation and deletion of indices.Resources - allows creation of new relations.Alteration - allows addition or deletion of attributes in a

41、relation.Drop - allows deletion of relations.Authorization Specification in SQLThe grant statement is used to confer authorizationgrant on to is:a user-idpublic, which allows all valid users the privilege grantedA role (more on this later)Granting a privilege on a view does not imply granting any pr

42、ivileges on the underlying relations.The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator).Privileges in SQLselect: allows read access to relation,or the ability to query using the viewExample: grant users U1, U2, and U3 select authoriz

43、ation on the instructor relation:grant select on instructor to U1, U2, U3insert: the ability to insert tuplesupdate: the ability to update using the SQL update statementdelete: the ability to delete tuples.all privileges: used as a short form for all the allowable privilegesRevoking Authorization in SQLThe revoke statement is used to revoke authorization.revoke on from Example:revoke select on branch from U1, U2, U3 may be all to revoke all privileges the revokee may hold.If includes public, all users lose the privilege

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論