数据库第四章课后题答案
- 格式:doc
- 大小:35.50 KB
- 文档页数:5
SolutionsChapter 44.1.14.1.2b)c)In c we assume that a phone and address can only bel ong to a sin gle customer (1-d)In d we assume that an address can only bel ong to one customer and a phone can exist at only one address.If the multiplicity of above relati on ships were m-to-n, the en tity set becomes weak and the key ssNo of customers will be needed as part of the composite key of the en tity set.In c&d, we convert attributes phones and addresses to entity sets. Since entity sets often become relations in relational design, we must con sider more efficie nt alter natives.In stead of query ing multiple tables where key values are duplicated, we can also modify attributes:(i)P hones attribute can be con verted into HomePho ne, OfficePh one and CellPh one.(ii) A multivalued attribute such as alias can be kept as an attribute where a sin gle colu mn can be used in relati onal desig n i.e. con cate nate all values. SQL4.1.34.1.4a)c)The relati on ship "played" betwee n Teams and Players is similar to relati on ship "plays" betwee n Teams and Players.b) 1 >: i .-I T mains Oo L UJT 曰 Pla.yor3uid^r 4.1.5 I ■acxnnxzres4.1.6 The in formatio n about childre n can be ascerta ined from motherOf and fatherOf relati on ships. Attribute ssNo is required since n ames are not uni que.People4.1.74.1.8a)(b)Family name Student;a 4.1.9 Assumpti ons A Professor only works in at most one departme nt. A course has at most one TA. A course is only taught by one professor and offered by one departme nt. Stude nts and professors have bee n assig ned uni que email ids. A course is uniquely identified by the course no, section no, and semester (e.g CS157-3 spring 09). ■ — Professors4.1.10Given that for each movie, a unique studio exists that produces the movie. Each star is contracted to at most one studio.But stars could be unemployed at a given time. Thus the four-way relationship in fig 4.6 can be easily into converted equivalent relationships.421Redu ndan cy: The owner address is repeated in AccSets and Addresses en tity sets. Simplicity: AccSets does not serve any useful purpose and the desig n can be more simply represe nted by creati ng man y-to-ma ny relati on ship betwee n Customers and Accou nts.Right kind of element: The entity set Addresses has a single attribute address.A customer cannot have more tha n one address.Hence address should be an attribute of en tity set Customers.Faithfulness: Customers cannot be uniquely identified by their names. In real world Customers would have a unique attribute such as ssNo or customerNo4.2.2Studios and Preside nts can be comb ined into one en tity set Studios with Preside nts beco ming an attribute of Studios un der follow ing circumsta nces: 1. The Presidents entity set only contains a simple attribute viz. presidentName. Additi onal attributes specific to Preside nts might justify making Preside nts into an en tity set.4.2.34.2.4 The en tity sets should have sin gle attribute.a)Stars: starNameb)Movies: movieNamec)Studios: studioName. However there exists a man y-to-ma ny relati on ship betwee n Studios and Con tracts. Hen ce, in additi on, we n eed more in formati on about studios in volved. If a con tract always in volves two studios, two attributes suchas produc in gStudio and starStudio can replace theStudios en tity set. If a con tact can be associated with at most five studios, it may be possible to replace the Studios en tity set by five attributes viz. studio1, studio2, studio3, studio4, and studio5. Alter nately, a composite attribute containing con cate nati on of all studio n ames in a con tact can be con sidered. A separator character such as "$" can be used. SQL allows search ing of such an attribute using query like '%keyword%'4.2.5From Augme ntati on rule of Fun cti onal Depe ndency, give nB -> M (B=Baby, M=Mother)the nBND -> M (N=Nurse, D=Doctor)Hence we can just put an arrow en ter ing mother.a) Put an arrow entering entity set Mothers for the simplest solution (As in fig.4.4, where a multi-way relati on ship was allowed, eve n though Movies alone could identify the Studio). However, we can display more accurate information with below figure.b)Mothersc)Aga in from Augme ntati on rule of Fun cti onal Depe ndency,give nBM -> Dthe nBMN -> DThus we can just add an arrow entering Doctors to fig 4.15. Below figure426a)Birthsb) Tran sitivity and Augme ntati on rules of Fun cti onal Depe ndency allow arrow en teri ng Mothers from Births. However, a new relati on ship in below figureDesig n flaws in abc above 1. As suggested above, using Tran sitivity and Augme ntati on rules of Fun cti onal Depe nden cy, much simpler desig n is possible.427In below figure there exists a many-to-one relati on ship betwee n Babies and Births and ano ther many-to-one relati on ship betwee n Births and Mothers. From tran sitivity of relati on ships, there is a many-to-one relati on ship betwee nBabies and Mothers. Hence a baby has a uni que mother while a birth can allowb)A captai n cannot exist without a team. However a player can (free age nt). A rece ntly formed (or defu net) team can exist without players or colors.c)Childre n can exist without mother and father (u432a)The keys of both E1 and E2 are required for uni quely ide ntify ing tuples in Rb)The key of E1c)The key of E2d)The key of either E1 or E24.3.3Special Case: All en tity sets have arrows going into them i.e. all relati on ships are 1-to-1Any KiOtherwise: Comb in ati on of all Ki's where there does not exist an arrow going from R to Ei.4.4.1No, grade is not part of the key for en rollme nts. The keys of Stude nts and442It is possible to make assig nment n umber a weak key of En rollme nts but this is not good desig n (redu ndancy since multiple assig nments corresp ond to a course). A new entity set Assignment is created and it is also a weak entity set. Hence the key attributes of Assig nment will come from the str ong en tity sets to whichEn rollme nts is conn ected i.e. stude ntID, dept, and CourseNo.a)b)4444.5.1Customers(SSNo, name,addr,pho ne)Flights (n umber,day,aircraft)Booki ngs(custSSNo,flightNo,flightDay,row,seat)Relati ons for toCust and toFlt relati on ships are not required since the weak en tity set Book ings already contains the keys of Customers and Flights.⑻(b)Schema is cha nged. Since toCust is no Ion ger an ide ntify ing relati on ship, SSNo is no longer a part of Bookings relation.Booki ngs(flightNo,flightDay,row,seat)ToCust(custSSNO,flightNo,flightDay,row,seat)The above relati ons are merged intoBooki ngs(flightNo,flightDay,row,seat,custSSNo)However custSSNo is no lon ger a key of Book ings relati on .It becomes a foreig n key in stead.4.5.3Ships(name, yearLaunched)SisterOf(name, sisterName)4.5.4(a)Stars(name,addr)Studios(name,addr) Movies(title,year,length,genre)Contracts(starName,movieTitle,movieYear,studioName,salary)Depending on other relationships not shown in ER diagram, studioName may not be required as a key of Contracts (or not even required as an attribute of Contracts).(b)Students(studentID)Courses(dept,courseNo)Enrollments(studentID,dept,courseNo,grade)(c)Departments(name) Courses(deptName,number)(d)Leagues(name)Teams(leagueName,teamName) Players(leagueName,teamName,playerName)4.6.1The weak relation Courses has the key from Depts along with number. Hence there is no relation for GivenBy relationship.(a)Depts(name, chair)Courses(number, deptName, room) LabCourses(number, deptName, allocation)(b)LabCourses has all the attributes of Courses.Depts(name, chair) Courses(number, deptName, room)LabCourses(number, deptName, room, allocation)(c)Courses and LabCourses are combined into one relation.Depts(name, chair)Courses(number, deptName, room, allocation)4.6.2(a)Person(name,address)ChildOf(personName,personAddress,childName,childAddress)Child(name,address,fatherName,fatherAddress,motherName,motherAddresss)Father(name,address,wifeName,wifeAddresss)Mother(name,address)Since FatherOf and MotherOf are many-one relationships from Child, there is no need for a separate relation for them. Similarly the one-one relationship Married can be included in Father (or Mother). ChildOf is a many-many relationship and needs a separate relation.However the ChildOf relation is not required since the relationship can be deduced from FatherOf and MotherOf relationships contained in Child relation.(b)A person cannot be both Mother and Father.Person(name,address)PersonChild(name,address)PersonChildFather(name,address)PersonChildMother(name,address)PersonFather(name,address)PersonMother(name,address)ChildOf(personName,personAddress,childName,childAddress)FatherOf(childName,childAddress,fatherName,fatherAddress)MotherOf(childName,childAddress,motherName,motherAddress)Married(husbandName,husbandAddress,wifeName,wifeAddress)The many-many ChildOf relationship again requires a relation.An entity belongs to one and only one class when using object-oriented approach. Hence, the many-one relations MotherOf and FatherOf could be added as attributes to PersonChild,PersonChildFather, and PersonChildMother relations. Similarly the Married relation can be added as attributes to PersonChildMother and PersonMother (or the corresponding father relations).(c)For the Person relation at least one of husband and wife attributes will be null. Person(personName,personAddress,fatherName,fatherAddress,motherName,motherAddresss,wifeName,wifeAddresss,husbandName,husbandAddress)ChildOf(personName,personAddress,childName,childAddress)4.6.3(a)People(name,fatherName,motherName)Males(name)Females(name)Fathers(name)Mothers(name)ChildOf(personName,childName)(b)People(name)PeopleMale(name)PeopleMaleFathers(name)PeopleFemale(name)PeopleFemaleMothers(name)ChildOf(personName,childName)FatherOf(childName,fatherName)MotherOf(childName,motherName)People cannot belong to both male and female branch of the ER diagram.Moreover since an entity belongs to one and only one class when using object- oriented approach, no entity belongs to People relation.Again we could replace MotherOf and FatherOf relations by adding as attributes to PeopleMale,PeopleMaleFathers,PeopleFemale, and PeopleFemaleMothers relations.(c)People(name,fatherName,motherName)ChildOf(personName,childName)4.6.4(a)Each entity set results in one relation. Thus both the minimum and maximum number of relations is e.The root relation has a attributes including k keys. Thus the minimum number of attributes is a. All other relations include the k keys from root along with their a attributes. Thus the maximum number of attributes is a+k.(b)The relation for root will have a attributes. The relation representing the whole tree will have e*a attributes.The n umber of relati ons will depe nd on the shape of the tree. A tree of e entities where only one child exists(say left child only) would have the minimum number of relations. Thus below figure will only contain 4 subtrees that contain rootE1,E1E2,E1E2E3, and E1E2E3E4. With e entity sets, minimum e relations are possible.E 1JET型The maximum n umber of subtrees result whe n all the en tities(except root) are at depth 1. Thus below figure will contain 8 subtrees that contain rootE1,E1E2,E1E3,E1E4,E1E2E3,E1E3E4,E1E2E4,and E1E2E3E4. With e entity sets, maximum 2A(e-1) relati ons are possible.(C)The nulls method always results in one relation and contains attributes from all e en tities i.e. e*a attributes. Summariz ing for a,b, and c above;#Comp onents #Relati onsMin Max Min MaxMethodstraight-E/R a a e eobject-orie nted a e*a e 2A(e-1)nulls e*a e*a 1 14.7.1b)c)d)MotherOf FatherOf4.7.5Males and Females subclasses are complete. Mothers and Fathers are partial. All subclasses are disj oint.Gradesa ProfessorsShips0…0■•出4.7.7 Works+email: PKTeach4.7.6CoursesOffers +no: PK +3ection : PK +s 巳m 巳s 七巳工:PJKsi^terShip original ShipWe con vert the ternary relati on ship Con tracts into three bi nary relati on ships betwee n a new en tity set Con tracts and existi ng en tity sets.Studios+n^me: PK ±addressMothers 0」Doctors-------------------Child +patient.TC: PK+doc-torIE: E 医4-add.res 5+ A dfir R.R a1- .1Births p. >Bdby Of +1 j_meOf Bi r th DoctcrFor.,Babies --- Nurses+babyID: PK u _ _ - ------------------------------ 1—+riur3eID ;: FK+addxes s NurseFor +羁立Movies +七itle: PK+year: PK+lengthContracts4.7.10A self-associati on Pare ntOf for en tity set people has multiplicity 0..2 at pare nt role end. In a Library database, if a patr on can loa n at most 12 books, them multiplicity is 0..12.For a FullTimeStude nts en tity set, a relati on ship of multiplicity 5..* must exist with Courses (A stude nt must take at least5 courses to be classified FullTime.Mothers^-patient ID: EK+己€1£1匸吕曰sMotherOfDoctors+doc 七口H ID: PKBaby OfBabies ♦+babyID: PK +addres3Births0.+1 iineOfBijsthDoctorForNurses+nuraeID : PKNurseForc)Customers(SSNo,name,addr,phone)Flights(number,day,aircraft) Bookings(row,seat,custSSNo,FlightNumber,FlightDay)Customers("SSNo",name,addr,phone) Flights("number","day",aircraft)Bookings(row,seat,"custSSNo","FlightNumber","FlightDay")4.8.2a)Movies(title,year,length,genre)Studios(name,address)Presidents(cert#,name,address) Owns(movieTitle,movieYear,studioName)Runs(studioName,presCert#)Movies("title","year",length,genre)Studios("name",address)Presidents("cert#",name,address) Owns("movieTitle","movieYear",studioName)Runs("studioName",presCert#)b)Since the subclasses are disjoint, Object Oriented Approach is used. The hierarchy is not complete. Hence four relations are required Movies(title,year,length,genre)MurderMysteries(title,year,length,genre,weapon) Cartoons(title,year,length,genre)Cartoon-MurderMysteries(title,year,length,genre,weapon)Movies("title","year",length,genre) MurderMysteries("title","year",length,genre,weapon)Cartoons("title","year",length,genre) Cartoon-MurderMysteries("title","year",length,genre,weapon)c)Customers(ssNo,name,phone,address)Accounts(number,balance,type)Owns(custSSNo,accountNumber)Customers("ssNo",name,phone,address)Accounts("number",balance,type)Owns("custSSNo","accountNumber")Teams(name,captainName)Players(name,teamName)Fans(name,favoriteColor)Colors(colorname)For Displays association,TeamColors(teamName,colorname)RootsFor(fanName,teamName)Admires(fanName,playerName)Teams("name",captainName)Players("name",teamName) Fans("name",favoriteColor)Colors("colorname")For Displays association,TeamColors("teamName","colorname")RootsFor("fanName","teamName")Admires("fanName","playerName")e)People(ssNo,name,fatherSSNo,motherSSNo)People("ssNo",name,fatherssNo,motherssNo)f)Students(email,name)Courses(no,section,semester,professorEmail)Departments(name)Professors(email,name,worksDeptName) Takes(letterGrade,studentEmail,courseNo,courseSection,courseSemester)Students("email",name)Courses("no","section","semester",professorEmail)Departments("name")Professors("email",name,worksDeptName) Takes(letterGrade,"studentEmail","courseNo","courseSection","courseSemester")4.8.3a)Each and every object is a member of exactly one subclass at leaf level. We have nine classes at the leaf of hierarchy. Hence we need nine relations.b)All objects only belong to one subclass and its ancestors. Hence, we need not consider every possible subtree but rather the total number of nodes in tree. Hence we need thirteen relations.c)We need all possible subtrees. Hence 218 relations are required.class Customer (key (ssNo)){attribute integer ssNo;attribute string name;attribute string addr;attribute string phone;relationship Set<Account> ownsAccts inverse Account::ownedBy;};class Account (key (number)){attribute integer number;attribute string type;attribute real balance;relationship Set<Customer> ownedBy inverse Customer::ownsAccts;};4.9.2a)Modify class Account to contain relationship Customer ownedBy (no Set)b)Also remove set in relationship ownsAccts of class Customer.c)ODL allows a collection of primitive types as well as structures. To classCustomer add following attributes in place of simple attributes addr and phone: Set<string phone> Set<Struct addr{string street,string city,string state}>d)ODL allows structures and collections recursively.Set<Struct addr{string street,string city,string state},Set<string phone>>Collections are allowed in ODL. Hence, Colors Set can become an attribute of Teams.class Colors(key(colorname)){attribute string colorname;relationship Set<Fans> FavoredBy inverse Fans::Favors;relationship set<Teams> DisplayedBy inverse Teams::Displays;};class Teams(key(name)){ attribute string name;relationship set<Colors> Displays inverse Colors::DisplayedBy;relationship set<Players> PlayedBy inverse Players::Plays;relationship PLayers CaptainedBy inverse Platyers::Captains;relationship set<Fans> RootedBy inverse Fans::Roots;};class Players(key(name)){attribute string name; relationship Set<Teams> Plays inverse Teams::PlayedBy;relationship Teams Captains inverse Teams::CaptainedBy;relationship Set<Fans> AdmiredBy inverse Fans::Admires;};class Fans(key(name)){attribute string name; relationship Colors Favors inverse Colors::FavoredBy;relationship Set<Teams> RootedBy inverse Teams::Roots;relationship Set<Players> Admires inverse Players::AdmiredBy;};4.9.4class Person {attribute string name;relationship Person motherOfinverse Person::childrenOfFemale; relationship Person fatherOfinverse Person::childrenOfMale; relationship Set<Person> childreninverse Person::parentsOf; relationship Set<Person> childrenOfFemaleinverse Person::motherOf; relationship Set<Person> childrenOfMaleinverse Person::fatherOf; relationship Set<Person> parentsOf inverse Person::children; };4.9.5The struct education{string degree,string school,string date} cannot have duplication.Hence use of Sets does not make any different as compared to bags, lists, or arrays.Lists will allow faster access/queries due to the already sorted nature.4.9.6a)class Departments(key (name)) { attribute string name;relationship Courses offersinverse Courses::offeredBy;};class Courses(key (number,offeredBy)) { attribute string number;relationship Departments offeredByinverse Departments::offers;};b)class Leagues (key (name)) { attribute name;relationship Teams containsinverse Teams::belongs;};class Teams(key (name,belongs)) {attribute name, relationship Leagues belongs inverse Leagues::contains;relationship Players playinverse Players::plays;};class Players (key(number,plays)) { attribute number, relationship Teams playsinverse Teams::play;};4.9.7class Students (key email) {attribute string email;attribute string name; relationship Courses isTAinverse Courses::TA;relationship Courses Takesinverse Courses::TakenBy;};class Professors (key email) {attribute string email;attribute string name; relationship Departments WorksForinverse Department::Works;relationship Courses Teachesinverse Courses::TaughtBy;};class Courses (key (no,semester,section)) {attribute string no;attribute string semester;attribute string section; relationship Students TA inverse Students::isTA;relationship Students TakenByinverse Students::Takes;relationship Professors TaughtByinverse Professors::Teaches;relationship Departments OfferedByinverse Departments::Offer;};class Departments (key name) {attribute name; relationship Courses Offer inverse Courses::OfferedBy;relationship Professors Worksinverse Professors::WorksFor;};4.9.8A relationship is its own inverse when for every attribute pair in the relationship, the inverse pair also exists. A relation with such a relationship is called symmetric in set theory. e.g. A relationship called SiblingOf in Person relation is its own inverse.4.10.1a)Customers(ssN o,n ame,addr,ph one)Accou nt(n umber,type,bala nee)Own s(ssNo,accou ntNumber)b)Accou nts( number,bala nce,type,ow nin gCustomerssNo)Customers(ssNo, name)Addresses(ow nerssNo,street,state,city)Phon es(ow nerssNo,street,state,city,ph on earea,ph oneno)We can remove Addresses relation since its attributes are a subset ofrelation Phon es.numberc)Fans(name,colors)RootedBy(fan_name,teamname)Admires(fan_name,playername)Players(name,teamname,is_captain) Teams(name)--remove subset of teamcolor Teamcolors(name,colorname) Colors(colorname)d)class Person {attribute string name;relationship Person motherOfinverse Person::childrenOfFemale;relationship Person fatherOfinverse Person::childrenOfMale;relationship Set<Person> childreninverse Person::parentsOf;relationship Set<Person> childrenOfFemaleinverse Person::motherOf;relationship Set<Person> childrenOfMaleinverse Person::fatherOf;relationship Set<Person> parentsOfinverse Person::children;};Person(name,mothername,fathername)The children relationship is many-many but the information can be deduced from Person relation. Hence below relation is redundant.Parent-Child(parent, child)4.10.2First consider each struct as if it were an atomic value i.e. key and value association pairs can be treated as two attributes. After applying normalization, the attributes can be replaced by the fields of the structs.4.10.3(a)Struct Card { string rank, string suit };(b)class Hand {attribute Set theHand;};(c)Hands(handId, rank, suit)Each tuple corresponds to one card of a hand. HandId is required key to identify a hand.(d)Hand contains an array of 5 elements class PokerHand{attribute Array Hand(Card card1,Card card2,Card card3,Card card4,Card card5)}PokerHandS(handId,rank1,suit1,,rank2,suit2,rank3,suit3,rank4,suit4,rank5,suit5 )(e)class Deal { attribute Set <Struct PlayerHand { string Player, Hand theHand }> theDeal;}(e)P okerDeal consist of a player and array of five card deal.class PokerDeal{string Player,attribute Array Hand(Card card1,Card card2,Card card3,Card card4,Card card5)}(f)Above can similarly be represented by key player and a value consistingof five element array.(h)dealID is a key for Deals. Thus the relations for classes Deals and Hands are: Deals(dealID, player, handID) Hands(handID, rank, suit)A simpler relation Deals below can also represents the classes:Deals(dealID, player, rank, suit)(i)The relation Deals(dealID,card) cannot identify the hand to which a card belongs. Also two attributes are required for a card;its rank and suit.Deals(dealID, handID, rank, suit)4.10.4(a)C(a, f, g)(b)C(a, f, g, count)(c)C(a, f, g, position)(d)C(a, f, g, i, j)。
第4章数据库安全性1 .什么是数据库的安全性?答:数据库的安全性是指保护数据库以防止不合法的使用所造成的数据泄露、更改或破坏。
2 .数据库安全性和计算机系统的安全性有什么关系?答:安全性问题不是数据库系统所独有的,所有计算机系统都有这个问题。
只是在数据库系统中大量数据集中存放,而且为许多最终用户直接共享,从而使安全性问题更为突出。
系统安全保护措施是否有效是数据库系统的主要指标之一。
数据库的安全性和计算机系统的安全性,包括操作系统、网络系统的安全性是紧密联系、相互支持的,3 .试述可信计算机系统评测标准的情况,试述TDI / TCSEC 标准的基本内容。
答:各个国家在计算机安全技术方面都建立了一套可信标准。
目前各国引用或制定的一系列安全标准中,最重要的是美国国防部(DoD )正式颁布的《DoD 可信计算机系统评估标准》(伽sted Co 哪uter system Evaluation criteria ,简称TcsEc ,又称桔皮书)。
(TDI / TCSEC 标准是将TcsEc 扩展到数据库管理系统,即《可信计算机系统评估标准关于可信数据库系统的解释》(Tmsted Database Interpretation 简称TDI , 又称紫皮书)。
在TDI 中定义了数据库管理系统的设计与实现中需满足和用以进行安全性级别评估的标准。
TDI 与TcsEc 一样,从安全策略、责任、保证和文档四个方面来描述安全性级别划分的指标。
每个方面又细分为若干项。
4 .试述T csEC ( TDI )将系统安全级别划分为4 组7 个等级的基本内容。
答:根据计算机系统对安全性各项指标的支持情况,TCSEC ( TDI )将系统划分为四组(division ) 7 个等级,依次是D 、C ( CI , CZ )、B ( BI , BZ , B3 )、A ( AI ) ,按系统可靠或可信程度逐渐增高。
这些安全级别之间具有一种偏序向下兼容的关系,即较高安全性级别提供的安全保护包含较低级别的所有保护要求,同时提供更多或更完善的保护能力。
第四章一、填空题1.椭圆框2.属性3.关系4.物理设计5.一个或多个二、判断题1.错2.对3.错4.对5.错三、选择题1. B2. B3. C4.B、C、D5.B、C四、简答题1.请简述数据库设计规范化的必要性。
答:数据库设计对数据的存储性能、数据的操作都有很大的关系。
为了避免不规范的数据库出现数据冗余,造成插入、删除、更新操作异常等情况,就要进行数据库设计规范化。
2.请分析数据库范式1NF、2NF、3NF的区别。
答:(1)1NF:数据库表的每一列都是不可分割的基本数据项。
(2)2NF:在满足1NF基础上,遵从唯一性,非主键字段需完全依赖主键(3)3NF:在满足2NF基础上,非主键字段不能相互依赖。
五、实训题1.请完成电子商务网站用户等级的数据表设计。
CREATE TABLE sh_user_level (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '等级id',name VARCHAR(20) NOT NULL DEFAULT '' COMMENT '等级名称',config VARCHAR(255) NOT NULL DEFAULT '' COMMENT '满足条件') DEFAULT CHARSET=utf8;12.请完成电子商务网站用户订阅、用户收藏的数据表设计。
# 订阅CREATE TABLE sh_user_subscribe (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '订阅id',email VARCHAR(60) COMMENT '邮箱地址',status INT COMMENT '是否确认,0未确认,1已确认',code VARCHAR(10) COMMENT '邮箱确认的验证码',add_time INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '开始订阅时间') DEFAULT CHARSET=utf8;# 收藏CREATE TABLE sh_user_favorite (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '收藏id',user_id INT UNSIGNED NOT NULL COMMENT '用户id',goods_id INT UNSIGNED NOT NULL COMMENT '商品id',add_time INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '收藏时间') DEFAULT CHARSET=utf8;2。
习题61、说明数据库设计的特点。
1)三分技术,七分管理,十二分基础数据2)综合性3)结构(数据)设计和行为(处理)设计相结合2、试述数据库设计的过程3、试述数据库设计过程的各个阶段设计内容。
1)需求分析阶段需求分析是对用户提出的各种要求加以分析,对各种原始数据加以综合、整理,是形成最终设计目标的首要阶段。
需求分析是整个设计过程的基础,是最困难、最耗费时间的一步。
2)概念结构设计阶段概念结构设计是对用户需求进行进一步抽象、归纳,并形成独立于DBMS和有关软、硬件的概念数据模型的设计过程。
3)逻辑结构设计阶段逻辑结构设计是将概念结构转换为某个DBMS所支持的数据模型,并对其进行优化的设计过程。
4)物理设计阶段数据库物理设计阶段,是将逻辑结构设计阶段所产生的逻辑数据模型,转换为某种计算机系统所支持的数据库物理结构的实现过程。
5)数据库实施阶段数据库实施阶段,即数据库调试、试运行阶段。
一旦数据库的物理结构形成,就可以用已选定的DBMS来定义、描述相应的数据库结构,装入数据库数据库,以生成完整的数据库,编制有关应用程序,进行联机调试并转入试运行,同时进行时间、空间等性能分析。
6)数据库运行和维护阶段数据库实施阶段结束,标志着数据库系统投入正常运行工作的开始。
在数据库系统运行过程中必须不断地对其进行评价、调整与修改。
4、需求分析中发现事实的方法有哪些?1)跟班作业。
通过亲身参加业务工作来观察和了解业务活动的情况。
2)开调查会。
通过与用户座谈来了解业务活动的情况及用户需求。
3)检查文档。
通过检查与当前系统有关的文档、表格、报告和文件等,进一步理解原系统,并有利于提供与原系统问题相关的业务信息。
4)问卷调查。
5、需求分析阶段的设计目标是什么?调查的内容是什么?需求分析阶段的目标是通过详细调查现实世界要处理的对象(组织、部门、企业等),充分了解原系统(手工系统或计算机系统)工作概况,确定企业的组织目标,明确用户的各种需求,进而确定新系统的功能,并把这些要求写成用户和数据库设计者都能够接受的文档。
1. SELECT*FROM Student结果:2. SELECT Sname 姓名,Sage 年龄FROM StudentWHERE Sdept='计算机系'结果:3. SELECT Sno 学号,Cno 课程号,Grade 成绩FROM SCWHERE Grade BETWEEN 70 AND 804. SELECT Sname 姓名,Sage 年龄FROM StudentWHERE Sdept='计算机系'AND Sage>=18 AND Sage<=20 AND Ssex='男'5. SELECT MAX(Grade)最高分数FROM SCWHERE Cno='c01'6. SELECT MAX(Sage)最大年龄,MIN(Sage)最小年龄FROM StudentWHERE Sdept='计算机系'7. SELECT Sdept 系名,COUNT(*)学生人数FROM StudentGROUP BY Sdept8. SELECT Cname 课程名,COUNT(*)选课门数,MAX(Grade)最高分FROM Course,SCGROUP BY Cname9. SELECT Sno 学号,COUNT(*)选课门数,SUM(Grade)总成绩FROM SCGROUP BY SnoORDER BY'选课门数'ASC10. SELECT Sno 学号,SUM(Grade)总成绩FROM SCGROUP BY SnoHAVING SUM(Grade)>20010.CREAT TABLE BOOK(Snobook nchar(6) PRIMARY KEY,Snamebook nvarchar(30) NBOT NULL,Writer char(10) NOT NULL,Time smalldatetime,Price numeric(3,1))CREAT TABLE BOOKSHOP(Snoshop nchar(6) PRIMARY KEY,Snameshop nvarchar(30) NOT NULL,Tel char(8)CHECK(Tel =0 AND Tel <=9),Place nchar(40),Snoemail char(6))CREAT TABLE BOOKSELL(Snobook nchar(6) NOT NULL,Snoshop nchar(6) NOT NULL,Selltime smalltime NOT NULL,Snosell tinyint,PRIMARY KEY (Snobook, Snoshop, Selltime),FOREIGN KEY (Snobook) REFERENCES BOOK(Snobook), FOREIGN KEY (Snoshop) REFERENCES BOOK(BOOKSHOP) )11.ALTER TABLE BOOKADD Nomber intADD CONSTRAINT DF-NomberCHECK (Nomber>1000)12.ALTER TABLE BOOKSHOPDROP COLUMN Tel13.ALTER TABLE BOOKSELLALTER COLUMN Snosell int。
数据库系统原理第四章关系运算课后习题答案4.1 名词解释(1)关系模型:用二维表格结构表示实体集,外键表示实体间联系的数据模型称为关系模型。
(2)关系模式:关系模式实际上就是记录类型。
它的定义包括:模式名,属性名,值域名以及模式的主键。
关系模式不涉及到物理存储方面的描述,仅仅是对数据特性的描述。
(3)关系实例:元组的集合称为关系和实例,一个关系即一张二维表格。
(4)属性:实体的一个特征。
在关系模型中,字段称为属性。
(5)域:在关系中,每一个属性都有一个取值范围,称为属性的值域,简称域。
(6)元组:在关系中,记录称为元组。
元组对应表中的一行;表示一个实体。
(7)超键:在关系中能唯一标识元组的属性集称为关系模式的超键。
(8)候选键:不含有多余属性的超键称为候选键。
(9)主键:用户选作元组标识的一个候选键为主键。
(单独出现,要先解释“候选键”)(10)外键:某个关系的主键相应的属性在另一关系中出现,此时该主键在就是另一关系的外键,如有两个关系S和SC,其中S#是关系S的主键,相应的属性S#在关系SC中也出现,此时S#就是关系SC的外键。
(11)实体完整性规则:这条规则要求关系中元组在组成主键的属性上不能有空值。
如果出现空值,那么主键值就起不了唯一标识元组的作用。
(12)参照完整性规则:这条规则要求“不引用不存在的实体”。
其形式定义如下:如果属性集K是关系模式R1的主键,K也是关系模式R2的外键,那么R2的关系中, K的取值只允许有两种可能,或者为空值,或者等于R1关系中某个主键值。
这条规则在使用时有三点应注意: 1)外键和相应的主键可以不同名,只要定义在相同值域上即可。
2)R1和R2也可以是同一个关系模式,表示了属性之间的联系。
3)外键值是否允许空应视具体问题而定。
(13)过程性语言:在编程时必须给出获得结果的操作步骤,即“干什么”和“怎么干”。
如Pascal和C语言等。
(14)非过程性语言:编程时只须指出需要什么信息,不必给出具体的操作步骤。
mysql数据库武洪萍版第四章习题与答案一.选择题1.下面哪种数字数据类型不可以存储数据256?(D)A.bigintB.intC.SmallintD.tinyint2.下面是有关主键和外键之间的关系描述,正确的是(AC)A.一个表最多只能有一个主键约束,多个外键约束。
B.一个表中最多只有一个外键约束,一个主键约束。
C.在定义主键外键约束时,应该首先定义主键约束,然后定义外键约束。
D.在定义主键外键约束时,应该首先定义主键约束,然后定义主键约束。
3.下面关于数据库中表的行和列的叙述正确的是(D)A.表中的行是有序的,列是无序的B.表中的列是有序的,行是无序的C.表中的行和列都是有序的D.表中的行和列都是无序的4.SQL语言的数据操作语句包括SELECT、INSERT、UPDATE、DELETE 等。
其中最重要的,也是使用最频繁的语句是(A)A.SELECTB.INSERTC.UPDATED.DELETE5.在下列SQL语句中,修改表结构的语句是(A)。
A.ALTERB.CREATEC.UPDATED.INSERT6.设有关系R(A,B,C)和S(C,D),与关系代数表达式πA,B,D(σR.C=S.C(R∞S)等价的SQL语句是(B)。
A.SELECT某FROMR,SWHERER.C=S.CB.SELECTA,B,DFROMR,SWHERER.C=.SELECTA,B,D FROMR,SWHERER=SD.SELECTA,BFROMRWHERE(SELECTDFROMSWHERER.C=S.C)7.设关系R(A,B,C)与SQL语句“SELECTDISTINSTAFROMRWHEREB=17”等价的关系代数表达式是(A)A.πA(σB=17(R))B.σB=17(πA(R))C.σB=17(πA.C(R))D.πA.C(σB=17(R))下面第(8)-(12)题,基于“学生-选课-课程”数据库中的3个关系。
第四章作业1.数据仓库的需求分析的任务是什么?P67需求分析的任务是通过详细调查现实世界要处理的对象(企业、部门用户等),充分了解源系统工作概况,明确用户的各种需求,为设计数据仓库服务。
概括地说,需求分析要明确用那些数据经过分析来实现用户的决策支持需求。
2.数据仓库系统需要确定的问题有哪些?P67、、(1)确定主题域a)明确对于决策分析最有价值的主题领域有哪些b)每个主题域的商业维度是那些?每个维度的粒度层次有哪些?c)制定决策的商业分区是什么?d)不同地区需要哪些信息来制定决策?e)对那个区域提供特定的商品和服务?(2)支持决策的数据来源a)那些源数据与商品的主题有关?b)在已有的报表和在线查询(OLTP)中得到什么样的信息?c)提供决策支持的细节程度是怎么样的?(3)数据仓库的成功标准和关键性指标a)衡量数据仓库成功的标准是什么?b)有哪些关键的性能指标?如何监控?c)对数据仓库的期望是什么?d)对数据仓库的预期用途有哪些?e)对计划中的数据仓库的考虑要点是什么?(4)数据量与更新频率a)数据仓库的总数据量有多少?b)决策支持所需的数据更新频率是多少?时间间隔是多长?c)每种决策分析与不同时间的标准对比如何?d)数据仓库中的信息需求的时间界限是什么?3.实现决策支持所需要的数据包括哪些内容?P68(1)源数据(2)数据转换(3)数据存储(4)决策分析4.概念:将需求分析过程中得到的用户需求抽象为计算机表示的信息结构,叫做概念模型。
特点:(1)能真实反映现实世界,能满足用户对数据的分析,达到决策支持的要求,它是现实世界的一个真实模型。
(2)易于理解,便利和用户交换意见,在用户的参与下,能有效地完成对数据仓库的成功设计。
(3)易于更改,当用户需求发生变化时,容易对概念模型修改和扩充。
(4)易于向数据仓库的数据模型(星型模型)转换。
5.用长方形表示实体,在数据仓库中就表示主题,椭圆形表示主题的属性,并用无向边把主题与其属性连接起来;用菱形表示主题之间的联系,用无向边把菱形分别与有关的主题连接;若主题之间的联系也具有属性,则把属性和菱形也用无向边连接上。
SolutionsChapter 4 4.1.14.1.2a)b)c)In c we assume that a phone and address can only belong to a single customer (1-m relationship represented by arrow into customer).d)In d we assume that an address can only belong to one customer and a phone can exist at only one address.If the multiplicity of above relationships were m-to-n, the entity set becomes weak and the key ssNo of customers will be needed as part of the composite key of the entity set.In c&d, we convert attributes phones and addresses to entity sets. Since entity sets often become relations in relational design,we must consider more efficient alternatives.Instead of querying multiple tables where key values are duplicated, we can also modify attributes:(i) Phones attribute can be converted into HomePhone, OfficePhone and CellPhone.(ii) A multivalued attribute such as alias can be kept as an attribute where a single column can be used in relational design i.e. concatenate all values. SQL allows a query "like '%Junius%'" to search the multiple values in a column alias.4.1.34.1.4a)c)The relationship "played" between Teams and Players is similar to relationship "plays" between Teams and Players.4.1.54.1.6 The information about children can be ascertained from motherOf and fatherOf relationships. Attribute ssNo is required since names are not unique.4.1.74.1.8a)(b)4.1.9AssumptionsA Professor only works in at most one department.A course has at most one TA.A course is only taught by one professor and offered by one department.Students and professors have been assigned unique email ids.A course is uniquely identified by the course no, section no, and semester (e.g. cs157-3 spring09).4.1.10Given that for each movie, a unique studio exists that produces the movie. Each star is contracted to at most one studio.But stars could be unemployed at a given time. Thus the four-way relationship in fig 4.6 can be easily into converted equivalent relationships.4.2.1Redundancy: The owner address is repeated in AccSets and Addresses entity sets. Simplicity: AccSets does not serve any useful purpose and the design can be more simply represented by creating many-to-many relationship between Customers and Accounts.Right kind of element: The entity set Addresses has a single attribute address. A customer cannot have more than one address.Hence address should be an attribute of entity set Customers.Faithfulness: Customers cannot be uniquely identified by their names. In real world Customers would have a unique attribute such as ssNo or customerNo4.2.2Studios and Presidents can be combined into one entity set Studios with Presidents becoming an attribute of Studios under following circumstances:1. The Presidents entity set only contains a simple attribute viz. presidentName. Additional attributes specific to Presidents might justify making Presidents into an entity set.4.2.34.2.4 The entity sets should have single attribute.a) Stars: starNameb) Movies: movieNamec) Studios: studioName. However there exists a many-to-many relationship between Studios and Contracts. Hence, in addition, we need more information about studios involved. If a contract always involves two studios, two attributes such as producingStudio and starStudio can replace theStudios entity set. If a contact can be associated with at most five studios, it may be possible to replace the Studios entity set by five attributes viz. studio1, studio2, studio3, studio4, and studio5. Alternately, a composite attribute containing concatenation of all studio names in a contact can be considered. A separator character such as "$" can be used. SQL allows searching of such an attribute using query like '%keyword%'4.2.5From Augmentation rule of Functional Dependency,givenB -> M (B=Baby, M=Mother)thenBND -> M (N=Nurse, D=Doctor)Hence we can just put an arrow entering mother.a) Put an arrow entering entity set Mothers for the simplest solution (As in fig. 4.4, where a multi-way relationship was allowed, even though Movies alone could identify the Studio). However, we can display more accurate information with below figure.c)Again from Augmentation rule of Functional Dependency,givenBM -> DthenBMN -> DThus we can just add an arrow entering Doctors to fig 4.15. Below figure represents more accurate information however.4.2.6a)b) Transitivity and Augmentation rules of Functional Dependency allow arrow entering Mothers from Births. However, a new relationship in below figure represents more accurate information.c)Design flaws in abc above 1. As suggested above, using Transitivity and Augmentation rules of Functional Dependency, much simpler design is possible.4.2.7In below figure there exists a many-to-one relationship between Babies and Births and another many-to-one relationship between Births and Mothers. From transitivity of relationships, thereis a many-to-one relationship between Babies and Mothers. Hence a baby has a unique mother while a birth can allow more than one baby.4.3.1a)b)A captain cannot exist without a team. However a player can (free agent). A recently formed (or defunct) team can exist without players or colors.c)Children can exist without mother and father (unknown).4.3.2a)The keys of both E1 and E2 are required for uniquely identifying tuples in Rb)The key of E1c)The key of E2d)The key of either E1 or E24.3.3Special Case: All entity sets have arrows going into them i.e. all relationships are 1-to-1Any KiOtherwise: Combination of all Ki's where there does not exist an arrow going from R to Ei.4.4.1No, grade is not part of the key for enrollments. The keys of Students and Courses become keys of the weak entity set Enrollments.4.4.2It is possible to make assignment number a weak key of Enrollments but this is not good design (redundancy since multiple assignments correspond to a course). A new entity set Assignment is created and it is also a weak entity set. Hence the key attributes of Assignment will come from the strong entity sets to which Enrollments is connected i.e. studentID, dept, and CourseNo.4.4.3a)b)4.4.4a)b)Customers(SSNo,name,addr,phone)Flights(number,day,aircraft)Bookings(custSSNo,flightNo,flightDay,row,seat)Relations for toCust and toFlt relationships are not required since the weak entity set Bookings already contains the keys of Customers and Flights.4.5.2(a)Schema is changed. Since toCust is no longer an identifying relationship, SSNo is no longer a part of Bookings relation.Bookings(flightNo,flightDay,row,seat)ToCust(custSSNO,flightNo,flightDay,row,seat)The above relations are merged intoBookings(flightNo,flightDay,row,seat,custSSNo)However custSSNo is no longer a key of Bookings relation. It becomes a foreign key instead.4.5.3Ships(name, yearLaunched)SisterOf(name, sisterName)4.5.4(a)Stars(name,addr)Studios(name,addr)Movies(title,year,length,genre)Contracts(starName,movieTitle,movieYear,studioName,salary)Depending on other relationships not shown in ER diagram, studioName may not be required as a key of Contracts (or not even required as an attribute of Contracts).(b)Students(studentID)Courses(dept,courseNo)Enrollments(studentID,dept,courseNo,grade)(c)Departments(name)Courses(deptName,number)Teams(leagueName,teamName)Players(leagueName,teamName,playerName)4.6.1The weak relation Courses has the key from Depts along with number. Hence there is no relation for GivenBy relationship.(a)Depts(name, chair)Courses(number, deptName, room)LabCourses(number, deptName, allocation)(b) LabCourses has all the attributes of Courses.Depts(name, chair)Courses(number, deptName, room)LabCourses(number, deptName, room, allocation)(c) Courses and LabCourses are combined into one relation.Depts(name, chair)Courses(number, deptName, room, allocation)4.6.2(a)Person(name,address)ChildOf(personName,personAddress,childName,childAddress)Child(name,address,fatherName,fatherAddress,motherName,motherAddresss)Father(name,address,wifeName,wifeAddresss)Mother(name,address)Since FatherOf and MotherOf are many-one relationships from Child, there is no need for a separate relation for them. Similarly the one-one relationship Married can be included in Father (or Mother). ChildOf is a many-many relationship and needs a separate relation.However the ChildOf relation is not required since the relationship can be deduced from FatherOf and MotherOf relationships contained in Child relation.(b)A person cannot be both Mother and Father.Person(name,address)PersonChild(name,address)PersonChildFather(name,address)PersonChildMother(name,address)PersonFather(name,address)PersonMother(name,address)ChildOf(personName,personAddress,childName,childAddress)FatherOf(childName,childAddress,fatherName,fatherAddress)MotherOf(childName,childAddress,motherName,motherAddress)Married(husbandName,husbandAddress,wifeName,wifeAddress)The many-many ChildOf relationship again requires a relation.An entity belongs to one and only one class when using object-oriented approach. Hence, the many-one relations MotherOf and FatherOf could be added as attributes toPersonChild,PersonChildFather, and PersonChildMother relations.Similarly the Married relation can be added as attributes to PersonChildMother and PersonMother (or the corresponding father relations).(c) For the Person relation at least one of husband and wife attributes will be null.Person(personName,personAddress,fatherName,fatherAddress,motherName,motherAddresss,wifeName,wife Addresss,husbandName,husbandAddress)ChildOf(personName,personAddress,childName,childAddress)4.6.3(a)People(name,fatherName,motherName)Males(name)Females(name)Fathers(name)Mothers(name)ChildOf(personName,childName)People(name)PeopleMale(name)PeopleMaleFathers(name)PeopleFemale(name)PeopleFemaleMothers(name)ChildOf(personName,childName)FatherOf(childName,fatherName)MotherOf(childName,motherName)People cannot belong to both male and female branch of the ER diagram.Moreover since an entity belongs to one and only one class when using object-oriented approach, no entity belongs to People relation.Again we could replace MotherOf and FatherOf relations by adding as attributes toPeopleMale,PeopleMaleFathers,PeopleFemale, and PeopleFemaleMothers relations.(c)People(name,fatherName,motherName)ChildOf(personName,childName)4.6.4(a)Each entity set results in one relation. Thus both the minimum and maximum number of relationsis e.The root relation has a attributes including k keys. Thus the minimum number of attributes is a. All other relations include the k keys from root along with their a attributes. Thus the maximum number of attributes is a+k.The relation for root will have a attributes. The relation representing the whole tree will have e*a attributes.The number of relations will depend on the shape of the tree. A tree of e entities where onlyone child exists(say left child only) would have the minimum number of relations. Thus below figure will only contain 4 subtrees that contain root E1,E1E2,E1E2E3, and E1E2E3E4. With eentity sets, minimum e relations are possible.The maximum number of subtrees result when all the entities(except root) are at depth 1. Thus below figure will contain 8 subtrees that contain rootE1,E1E2,E1E3,E1E4,E1E2E3,E1E3E4,E1E2E4,and E1E2E3E4. With e entity sets, maximum 2^(e-1)relations are possible.(c)The nulls method always results in one relation and contains attributes from all e entities i.e. e*a attributes.Summarizing for a,b, and c above;#Components #RelationsMin Max Min MaxMethodstraight-E/R a a e eobject-oriented a e*a e 2^(e-1)nulls e*a e*a 1 14.7.14.7.2a)b)c)d)4.7.34.7.44.7.5Males and Females subclasses are complete. Mothers and Fathers are partial. All subclasses are disjoint.4.7.64.7.74.7.8We convert the ternary relationship Contracts into three binary relationships between a new entity set Contracts and existing entity sets.4.7.9a)c)4.7.10A self-association ParentOf for entity set people has multiplicity 0..2 at parent role end.In a Library database, if a patron can loan at most 12 books, them multiplicity is 0..12.For a FullTimeStudents entity set, a relationship of multiplicity 5..* must exist with Courses(A student must take at least5 courses to be classified FullTime.4.8.1Customers(SSNo,name,addr,phone)Flights(number,day,aircraft)Bookings(row,seat,custSSNo,FlightNumber,FlightDay)Customers("SSNo",name,addr,phone)Flights("number","day",aircraft)Bookings(row,seat,"custSSNo","FlightNumber","FlightDay")4.8.2a)Movies(title,year,length,genre)Studios(name,address)Presidents(cert#,name,address)Owns(movieTitle,movieYear,studioName)Runs(studioName,presCert#)Movies("title","year",length,genre)Studios("name",address)Presidents("cert#",name,address)Owns("movieTitle","movieYear",studioName)Runs("studioName",presCert#)b)Since the subclasses are disjoint, Object Oriented Approach is used. The hierarchy is not complete. Hence four relations are required Movies(title,year,length,genre)MurderMysteries(title,year,length,genre,weapon)Cartoons(title,year,length,genre)Cartoon-MurderMysteries(title,year,length,genre,weapon)Movies("title","year",length,genre)MurderMysteries("title","year",length,genre,weapon)Cartoons("title","year",length,genre)Cartoon-MurderMysteries("title","year",length,genre,weapon)c)Customers(ssNo,name,phone,address)Accounts(number,balance,type)Owns(custSSNo,accountNumber)Customers("ssNo",name,phone,address)Accounts("number",balance,type)Owns("custSSNo","accountNumber")d)Teams(name,captainName)Players(name,teamName)Fans(name,favoriteColor)Colors(colorname)For Displays association,TeamColors(teamName,colorname)RootsFor(fanName,teamName)Admires(fanName,playerName)Teams("name",captainName)Players("name",teamName)Fans("name",favoriteColor)Colors("colorname")For Displays association,TeamColors("teamName","colorname")RootsFor("fanName","teamName")Admires("fanName","playerName")e)People(ssNo,name,fatherSSNo,motherSSNo)People("ssNo",name,fatherssNo,motherssNo)f)Students(email,name)Courses(no,section,semester,professorEmail)Departments(name)Professors(email,name,worksDeptName)Takes(letterGrade,studentEmail,courseNo,courseSection,courseSemester)Students("email",name)Courses("no","section","semester",professorEmail)Departments("name")Professors("email",name,worksDeptName)Takes(letterGrade,"studentEmail","courseNo","courseSection","courseSemester")4.8.3a)Each and every object is a member of exactly one subclass at leaf level. We have nine classes at the leaf of hierarchy. Hence we need nine relations.b)All objects only belong to one subclass and its ancestors. Hence, we need not consider every possible subtree but rather the total number of nodes in tree.Hence we need thirteen relations.c)We need all possible subtrees. Hence 218 relations are required.4.9.1class Customer (key (ssNo)){attribute integer ssNo;attribute string name;attribute string addr;attribute string phone;relationship Set<Account> ownsAcctsinverse Account::ownedBy;};class Account (key (number)){attribute integer number;attribute string type;attribute real balance;relationship Set<Customer> ownedByinverse Customer::ownsAccts;};4.9.2a)Modify class Account to contain relationship Customer ownedBy (no Set)b)Also remove set in relationship ownsAccts of class Customer.c)ODL allows a collection of primitive types as well as structures. To class Customer add following attributes in place of simple attributes addr and phone:Set<string phone>Set<Struct addr{string street,string city,string state}>d)ODL allows structures and collections recursively.Set<Struct addr{string street,string city,string state},Set<string phone>>4.9.3Collections are allowed in ODL. Hence, Colors Set can become an attribute of Teams. class Colors(key(colorname)){attribute string colorname;relationship Set<Fans> FavoredByinverse Fans::Favors;relationship set<Teams> DisplayedByinverse Teams::Displays;};class Teams(key(name)){attribute string name;relationship set<Colors> Displaysinverse Colors::DisplayedBy;relationship set<Players> PlayedByinverse Players::Plays;relationship PLayers CaptainedByinverse Platyers::Captains;relationship set<Fans> RootedByinverse Fans::Roots;};class Players(key(name)){attribute string name;relationship Set<Teams> Playsinverse Teams::PlayedBy;relationship Teams Captainsinverse Teams::CaptainedBy;relationship Set<Fans> AdmiredByinverse Fans::Admires;};class Fans(key(name)){attribute string name;relationship Colors Favorsinverse Colors::FavoredBy;relationship Set<Teams> RootedByinverse Teams::Roots;relationship Set<Players> Admiresinverse Players::AdmiredBy;};4.9.4class Person {attribute string name;relationship Person motherOfinverse Person::childrenOfFemale;relationship Person fatherOfinverse Person::childrenOfMale;relationship Set<Person> childreninverse Person::parentsOf;relationship Set<Person> childrenOfFemaleinverse Person::motherOf;relationship Set<Person> childrenOfMaleinverse Person::fatherOf;relationship Set<Person> parentsOfinverse Person::children;};4.9.5The struct education{string degree,string school,string date} cannot have duplication. Hence use of Sets does not make any different as compared to bags, lists, or arrays. Lists will allow faster access/queries due to the already sorted nature.4.9.6a)class Departments(key (name)) {attribute string name;relationship Courses offersinverse Courses::offeredBy;};class Courses(key (number,offeredBy)) {attribute string number;relationship Departments offeredByinverse Departments::offers;};b)class Leagues (key (name)) {attribute name;relationship Teams containsinverse Teams::belongs;};class Teams(key (name,belongs)) {attribute name,relationship Leagues belongsinverse Leagues::contains;relationship Players playinverse Players::plays;};class Players (key(number,plays)) {attribute number,relationship Teams playsinverse Teams::play;};4.9.7class Students (key email) {attribute string email;attribute string name;relationship Courses isTAinverse Courses::TA;relationship Courses Takesinverse Courses::TakenBy;};class Professors (key email) {attribute string email;attribute string name;relationship Departments WorksForinverse Department::Works;relationship Courses Teachesinverse Courses::TaughtBy;};class Courses (key (no,semester,section)) {attribute string no;attribute string semester;attribute string section;relationship Students TAinverse Students::isTA;relationship Students TakenByinverse Students::Takes;relationship Professors TaughtByinverse Professors::Teaches;relationship Departments OfferedByinverse Departments::Offer;};class Departments (key name) {attribute name;relationship Courses Offerinverse Courses::OfferedBy;relationship Professors Worksinverse Professors::WorksFor;};4.9.8A relationship is its own inverse when for every attribute pair in the relationship, the inverse pair also exists. A relation with such a relationship is called symmetric in set theory. e.g. A relationship called SiblingOf in Person relation is its own inverse.4.10.1a)Customers(ssNo,name,addr,phone)Account(number,type,balance)Owns(ssNo,accountNumber)b)Accounts(number,balance,type,owningCustomerssNo)Customers(ssNo,name)Addresses(ownerssNo,street,state,city)Phones(ownerssNo,street,state,city,phonearea,phoneno)We can remove Addresses relation since its attributes are a subset of relation Phones.Fans(name,colors)RootedBy(fan_name,teamname)Admires(fan_name,playername)Players(name,teamname,is_captain)Teams(name)--remove subset of teamcolorTeamcolors(name,colorname)Colors(colorname)d)class Person {attribute string name;relationship Person motherOfinverse Person::childrenOfFemale;relationship Person fatherOfinverse Person::childrenOfMale;relationship Set<Person> childreninverse Person::parentsOf;relationship Set<Person> childrenOfFemaleinverse Person::motherOf;relationship Set<Person> childrenOfMaleinverse Person::fatherOf;relationship Set<Person> parentsOfinverse Person::children;};Person(name,mothername,fathername)The children relationship is many-many but the information can be deduced from Person relation. Hence below relation is redundant.Parent-Child(parent, child)4.10.2First consider each struct as if it were an atomic value i.e. key and value association pairs can be treated as two attributes. After applying normalization,the attributes can be replaced by the fields of the structs.4.10.3(a)Struct Card { string rank, string suit };(b)class Hand {attribute Set theHand;};(c)Hands(handId, rank, suit)Each tuple corresponds to one card of a hand. HandId is required key to identify a hand.(d) Hand contains an array of 5 elementsclass PokerHand{attribute Array Hand(Card card1,Card card2,Card card3,Card card4,Card card5)} PokerHandS(handId,rank1,suit1,,rank2,suit2,rank3,suit3,rank4,suit4,rank5,suit5)(e)class Deal {attribute Set <Struct PlayerHand { string Player, Hand theHand } > theDeal;}(f) PokerDeal consist of a player and array of five card deal.class PokerDeal{string Player,attribute Array Hand(Card card1,Card card2,Card card3,Cardcard4,Card card5)}(g) Above can similarly be represented by key player and a value consisting of five element array.(h)dealID is a key for Deals. Thus the relations for classes Deals and Hands are:Deals(dealID, player, handID)Hands(handID, rank, suit)A simpler relation Deals below can also represents the classes:Deals(dealID, player, rank, suit)(i)The relation Deals(dealID,card) cannot identify the hand to which a card belongs. Also two attributes are required for a card;its rank and suit.Deals(dealID, handID, rank, suit)4.10.4(a)C(a, f, g)(b)C(a, f, g, count)(c)C(a, f, g, position)(d)C(a, f, g, i, j)。
8. 有如下三个基本表:
student(sno,sname,ssex,sage,sdept)
course(cno,cname,teachername,credit)
sc(sno,cno,grade)
其中teachername代表授课教师名,其他属性的含义与本章中的例子一致。
请完成以下查询:(1)查询姓李的男同学的人数。
select count(*)
From student
where sname like ‘李%’and ssex=’男’
(2)查询003号课程的最低分。
select min(grade)
from sc
where cno=’003’
(3)查询每位同学的平均分。
select sno,avg(grade)
from sc
group by sno
(4)查询每位同学选修的课程门数。
select sno,count(cno)
from sc
group by sno
(5)查询总分最高的学生的学号。
select sno
from sc
group by sno
having sum(grade)=(select top 1 sum(grade)
from sc
group by sno
order by sum(grade)desc
)
(6)查询至少选修三门课程的学生的学号。
select sno
from sc
group by sno
having count(cno)>=3
(7)统计有学生选修的课程的门数。
select count(distinct cno)
from sc
(8)统计每门课程的学生选修人数,超过20人的课程才统计,要求输出课程号和选修人数,查询结果按人数降序排列,如果人数相同,按课程号升序排列。
select cno,count(sno)
from sc
group by cno
having count(sno)>=20
order by count(sno) desc,cno asc
(9)查询数据库原理与应用80分以上的学生姓名。
select sname
from student,sc,course
where student.sno=sc.sno and o=o
and cname=’数据库原理与应用’and grade>=80
(10)查询每门课程的课程名及选修人数。
select cname,count(sno)
from course,sc
where o=o
group by cname
(11)查询总学分超过30学分的学生的学号、姓名和总学分。
select student.sno,sname,sum(credit)
from student,sc,course
where student.sno=sc.sno and o=o
group by student.sno,sname
having sum(credit)>=30
(12)查询张明同学没有选修的课程号。
select cno
from course
where cno not in(
select cno
from sc
where sno in(select sno
from student
where sname=’张明’)
)
(13)查询选修课程包含李慧老师所讲授课程的学生学号。
select sno
from student
where not exists
(select *
from course
where teachername=’李慧’ and not exists
(select *
from sc
where sno=student.sno and cno=o)
)
(14)查询选修008号课程的学生的平均年龄。
select avg(sage)
from sc,student
where sc.sno=student.sno
and cno=’008’
(15)查询李慧老师讲授的每门课程的学生的平均成绩。
select o,avg(grade)
from student,sc,course
where student.sno=sc.sno and o=o
and teachername=’李慧’
group by o
9. 对8题的表完成以下更新:
(1)向student表增加一条记录。
insert into student
values(‘1111111’,’张三’,‘男’,22,‘计算机系’)
(2)在student表中删除李明同学的信息。
delete from student
where sname=’李明’
(3)查询每门课程成绩都在80分以上的学生的学号、姓名和性别,并将查询结果存入表student2(sno,sname,sex)中。
insert into student2(sno,sname,ssex)
select student.sno,sname,ssex
from student,sc
where student.sno=sc.sno
group by student.sno,sname,ssex
having min(grade)>=80
(4)在sc表中删除成绩为空的元组。
delete from sc
where grade is null
(5)删除王娜同学的选课记录。
delete from sc
where sno in(select sno
from student
where sname=’王娜’
)
(6)把选修数据库不及格的成绩改为空值。
update sc
set grade=null
where grade<60 and cno in(select cno
from course
where cname=’数据库’
)
(7)把低于总平均成绩的女生成绩提高10%。
update sc
set grade=grade*1.1
where sno in(select sno from student where ssex=’女’) and grade<(select avg(grade) from sc)
(8)在sc表中修改005号课程的成绩,如果成绩小于75分提高5%。
update sc
set grade=grade*1.05
where cno=’005’and grade<75。