版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter 2: Relational ModelChapter 2: Relational ModelStructure of Relational DatabasesFundamental Relational-Algebra-OperationsAdditional Relational-Algebra-OperationsExtended Relational-Algebra-OperationsNull ValuesModification of the DatabaseExample of a RelationBasic StructureFormally, given set
2、s D1, D2, . Dn a relation r is a subset of D1 x D2 x x DnThus, a relation is a set of n-tuples (a1, a2, , an) where each ai DiExample: Ifcustomer_name = Jones, Smith, Curry, Lindsaycustomer_street = Main, North, Parkcustomer_city = Harrison, Rye, PittsfieldThen r = (Jones, Main, Harrison), (Smith, N
3、orth, Rye), (Curry, North, Rye), (Lindsay, Park, Pittsfield) is a relation over customer_name x customer_street x customer_cityAttribute TypesEach attribute of a relation has a nameThe set of allowed values for each attribute is called the domain of the attributeAttribute values are (normally) requi
4、red to be atomic; that is, indivisibleNote: multivalued attribute values are not atomicNote: composite attribute values are not atomicThe special value null is a member of every domainThe null value causes complications in the definition of many operationsWe shall ignore the effect of null values in
5、 our main presentation and consider their effect laterRelation SchemaA1, A2, , An are attributesR = (A1, A2, , An ) is a relation schemaExample:Customer_schema = (customer_name, customer_street, customer_city)r(R) is a relation on the relation schema RExample:customer (Customer_schema)Relation Insta
6、nceThe current values (relation instance) of a relation are specified by a tableAn element t of r is a tuple, represented by a row in a tableJonesSmithCurryLindsaycustomer_nameMainNorthNorthParkcustomer_streetHarrisonRyeRyePittsfieldcustomer_citycustomerattributes(or columns)tuples(or rows)Relations
7、 are Unordered Order of tuples is irrelevant (tuples may be stored in an arbitrary order) Example: account relation with unordered tuplesDatabaseA database consists of multiple relationsInformation about an enterprise is broken up into parts, with each relation storing one part of the informationacc
8、ount : stores information about accounts depositor : stores information about which customer owns which account customer : stores information about customersStoring all information as a single relation such as bank(account_number, balance, customer_name, .)results inrepetition of information (e.g.,
9、a customers own several accounts)the need for null values (e.g., represent a customer without an account)Normalization theory (Chapter 7) deals with how to design relational schemasThe customer RelationThe depositor RelationKeysLet K RK is a superkey of R if values for K are sufficient to identify a
10、 unique tuple of each possible relation r(R) by “possible r ” we mean a relation r that could exist in the enterprise we are modeling.Example: customer_name, customer_street and customer_name are both superkeys of Customer, if no two customers can possibly have the same name.K is a candidate key if
11、K is minimalExample: customer_name is a candidate key for Customer, since it is a superkey (assuming no two customers can possibly have the same name), and no subset of it is a superkey.Primary Key Query LanguagesLanguage in which user requests information from the database.Categories of languagesPr
12、oceduralNon-procedural, or declarative“Pure” languages:Relational algebraTuple relational calculusDomain relational calculusPure languages form underlying basis of query languages that people use.Relational AlgebraProcedural languageSix basic operatorsselect: project: union: set difference: Cartesia
13、n product: xrename: The operators take one or two relations as inputs and produce a new relation as a result.Select Operation ExampleRelation rABC=B D 5 (r)ABCD123710Select OperationNotation: p(r)p is called the selection predicateDefined as: p(r) = t | t r and p(t)Where p is a formula
14、in propositional calculus consisting of terms connected by : (and), (or), (not)Each term is one of:op or where op is one of: =, , , . 1200 (loan)loan_number (amount 1200 (loan)Example QueriesFind the names of all customers who have a loan, an account, or both, from the bankcustomer_name (borrower) c
15、ustomer_name (depositor)Example QueriesFind the names of all customers who have a loan at the Perryridge branch. Find the names of all customers who have a loan at the Perryridge branch but do not have an account at any branch of the bank.customer_name (branch_name = “Perryridge” (borrower.loan_numb
16、er = loan.loan_number(borrower x loan) customer_name(depositor)customer_name (branch_name=“Perryridge” (borrower.loan_number = loan.loan_number(borrower x loan)Example QueriesFind the names of all customers who have a loan at the Perryridge branch. Query 2 customer_name(loan.loan_number = borrower.l
17、oan_number ( (branch_name = “Perryridge” (loan) x borrower)Query 1 customer_name (branch_name = “Perryridge” ( borrower.loan_number = loan.loan_number (borrower x loan)Example QueriesFind the largest account balanceStrategy:Find those balances that are not the largestRename account relation as d so
18、that we can compare each account balance with all othersUse set difference to find those account balances that were not found in the earlier step. The query is: balance(account) - account.balance (account.balance d.balance (account x rd (account)Formal DefinitionA basic expression in the relational
19、algebra consists of either one of the following:A relation in the databaseA constant relationLet E1 and E2 be relational-algebra expressions; the following are all relational-algebra expressions:E1 E2E1 E2E1 x E2p (E1), P is a predicate on attributes in E1s(E1), S is a list consisting of some of the
20、 attributes in E1 x (E1), x is the new name for the result of E1Additional OperationsWe define additional operations that do not add any power to therelational algebra, but that simplify common queries.Set intersectionNatural joinDivisionAssignmentSet-Intersection OperationNotation: r sDefined as:r
21、s = t | t r and t s Assume: r, s have the same arity attributes of r and s are compatibleNote: r s = r (r s)Set-Intersection Operation ExampleRelation r, s:r sA B121A B23rsA B 2 Notation: r sNatural-Join OperationLet r and s be relations on schemas R and S respectively. Then, r s is a relation on sc
22、hema R S obtained as follows:Consider each pair of tuples tr from r and ts from s. If tr and ts have the same value on each of the attributes in R S, add a tuple t to the result, wheret has the same value as tr on rt has the same value as ts on sExample:R = (A, B, C, D)S = (E, B, D)Result schema = (
23、A, B, C, D, E)r s is defined as: r.A, r.B, r.C, r.D, s.E (r.B = s.B r.D = s.D (r x s)Natural Join Operation ExampleRelations r, s:AB12412CDaababB13123DaaabbErAB11112CDaaaabEsr sDivision OperationNotation: Suited to queries that include the phrase “for all”.Let r and s be relations on schemas R and S
24、 respectively whereR = (A1, , Am , B1, , Bn )S = (B1, , Bn)The result of r s is a relation on schemaR S = (A1, , Am)r s = t | t R-S (r) u s ( tu r ) Where tu means the concatenation of tuples t and u to produce a single tupler s Division Operation ExampleRelations r, s:r s:AB12AB12311134612rsAnother
25、 Division ExampleABaaaaaaaaCDaabababbE11113111Relations r, s:r s:DabE11ABaaCrsDivision Operation (Cont.)Property Let q = r sThen q is the largest relation satisfying q x s rDefinition in terms of the basic algebra operationLet r(R) and s(S) be relations, and let S Rr s = R-S (r ) R-S ( ( R-S (r ) x
26、s ) R-S,S(r )To see whyR-S,S (r) simply reorders attributes of rR-S (R-S (r ) x s ) R-S,S(r) ) gives those tuples t in R-S (r ) such that for some tuple u s, tu r.Assignment OperationThe assignment operation () provides a convenient way to express complex queries. Write query as a sequential program
27、 consisting ofa series of assignments followed by an expression whose value is displayed as a result of the query.Assignment must always be made to a temporary relation variable.Example: Write r s as temp1 R-S (r ) temp2 R-S (temp1 x s ) R-S,S (r )result = temp1 temp2The result to the right of the i
28、s assigned to the relation variable on the left of the .May use variable in subsequent expressions.Bank Example QueriesFind the names of all customers who have a loan and an account at bank.customer_name (borrower) customer_name (depositor)Find the name of all customers who have a loan at the bank,
29、loan number and the loan amount.Query 2 customer_name, branch_name (depositor account) temp(branch_name) (“Downtown” ), (“Uptown” )Note that Query 2 uses a constant relation.Bank Example QueriesFind all customers who have an account from at least the “Downtown” and the Uptown” branches.Query 1custom
30、er_name (branch_name = “Downtown” (depositor account ) customer_name (branch_name = “Uptown” (depositor account)Find all customers who have an account at all branches located in Brooklyn city.Example Queriescustomer_name, branch_name (depositor account) branch_name (branch_city = “Brooklyn” (branch)
31、Extended Relational-Algebra-OperationsGeneralized ProjectionAggregate FunctionsOuter JoinGeneralized ProjectionExtends the projection operation by allowing arithmetic functions to be used in the projection list.E is any relational-algebra expressionEach of F1, F2, , Fn are are arithmetic expressions
32、 involving constants and attributes in the schema of E.Given relation credit_info(customer_name, limit, credit_balance), find how much more each person can spend: customer_name, limit credit_balance (credit_info)Aggregate Functions and OperationsAggregation function takes a collection of values and
33、returns a single value as a result.avg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of valuesAggregate operation in relational algebra E is any relational-algebra expressionG1, G2 , Gn is a list of attributes on which to group (can be empty)Each Fi is an aggregat
34、e functionEach Ai is an attribute nameAggregate Operation ExampleRelation r:ABC77310g sum(c) (r)sum(c )27Aggregate Operation ExampleRelation account grouped by branch-name:branch_name g sum(balance) (account)branch_nameaccount_numberbalancePerryridgePerryridgeBrightonBrightonRedwoodA-102A-201A-217A-
35、215A-222400900750750700branch_namesum(balance)PerryridgeBrightonRedwooggregate Functions (Cont.)Result of aggregation does not have a nameCan use rename operation to give it a nameFor convenience, we permit renaming as part of aggregate operationbranch_name g sum(balance) as sum_balance
36、 (account)Outer 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:null signifies that the value is unknown or does not exist All
37、comparisons involving null are (roughly speaking) false by definition.We shall study precise meaning of comparisons with nulls laterOuter Join ExampleRelation loanRelation borrowercustomer_nameloan_numberJonesSmithHayesL-170L-230L-155300040001700loan_numberamountL-170L-230L-260branch_nameDowntownRed
38、woodPerryridgeOuter Join ExampleInner Joinloan Borrowerloan_numberamountL-170L-23030004000customer_nameJonesSmithbranch_nameDowntownRedwoodJonesSmithnullloan_numberamountL-170L-230L-260300040001700customer_namebranch_nameDowntownRedwoodPerryridge Left Outer Join loan BorrowerOuter Join Exampleloan_n
39、umberamountL-170L-230Lullcustomer_nameJonesSmithHayesbranch_nameDowntownRedwoodnullloan_numberamountL-170L-230L-260L-155300040001700nullcustomer_nameJonesSmithnullHayesbranch_nameDowntownRedwoodPerryridgenull Full Outer Join loan borrower Right Outer Join loan borrowerNull ValuesIt is p
40、ossible for tuples to have a null value, denoted by null, for some of their attributesnull signifies an unknown value or that a value does not exist.The result of any arithmetic expression involving null is null.Aggregate functions simply ignore null values (as in SQL)For duplicate elimination and g
41、rouping, null is treated like any other value, and two nulls are assumed to be the same (as in SQL)Null ValuesComparisons with null values return the special truth value: unknownThree-valued logic using the truth value unknown:OR: (unknown or true) = true, (unknown or false) = unknown (unknown or un
42、known) = unknownAND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknownNOT: (not unknown) = unknownIn SQL “P is unknown” evaluates to true if predicate P evaluates to unknownModification of the DatabaseThe content of the database may be modified using the foll
43、owing operations:DeletionInsertionUpdatingAll these operations are expressed using the assignment operator.DeletionA delete request is expressed similarly to a query, except instead of displaying tuples to the user, the selected tuples are removed from the database.Can delete only whole tuples; cann
44、ot delete values on only particular attributesA deletion is expressed in relational algebra by:r r Ewhere r is a relation and E is a relational algebra query.Deletion ExamplesDelete all account records in the Perryridge branch. Delete all loan records with amount in the range of 0 to 50loan loan amo
45、unt 0and amount 50 (loan)account account branch_name = “Perryridge” (account )InsertionTo insert data into a relation, we either:specify a tuple to be insertedwrite a query whose result is a set of tuples to be insertedin relational algebra, an insertion is expressed by:r r Ewhere r is a relation an
46、d E is a relational algebra expression.The insertion of a single tuple is expressed by letting E be a constant relation containing one tuple. Insertion ExamplesInsert information in the database specifying that Smith has $1200 in account A-973 at the Perryridge branch. Provide as a gift for all loan
47、 customers in the Perryridge branch, a $200 savings account. Let the loan number serve as the account number for the new savings account.account account (“Perryridge”, A-973, 1200)depositor depositor (“Smith”, A-973)r1 (branch_name = “Perryridge” (borrower loan)account account (loan_number, branch_name (r1) x(200)depositor depositor customer_name, loan_number (r1)UpdatingA mechanism to change a value in a tuple without charging all values in
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 《土木工程材料》课件 06建筑钢材
- 消防工作绩效总结及展望
- 《土木工程材料》-陈正 习题及解答
- 医院工作总结儿科工作总结呵护孩子健康
- 护士查房制作教程
- 质量改善措施总结
- 环卫年终工作总结美篇(15篇)
- 物业公司前台工作总结(22篇)
- 信息技术-基础模块-《 运用典型算法》教学设计5.3
- 《诗词曲五首》公开课教学课件第1课时【部编人教版九年级语文下册】
- 9.3一元一次不等式组解法市公开课一等奖省赛课微课金奖课件
- (2024年)放射科应急预案演练(大全)
- 校园环境装饰设计说明书
- 项目攻坚实施方案
- 内镜室护理质量持续改进
- 发电厂火灾事故处置预案范文(四篇)
- 2024届浙江省中考物理全真模拟试卷含解析
- MOOC 化学教学论手持技术数字化实验-华南师范大学 中国大学慕课答案
- 上春山 二声部合唱简谱
- 演出经纪人之演出经纪实务考试题库800道【培优】
- 2024水电站智能巡检系统技术规范
评论
0/150
提交评论