《數(shù)據(jù)庫系統(tǒng)》教學課件
數(shù)據(jù)庫系統(tǒng)教學課件,數(shù)據(jù)庫系統(tǒng),數(shù)據(jù)庫,系統(tǒng),教學,課件
The Relational ModelJianlin FengSchool of SoftwareSUN YAT-SEN UNIVERSITYRelational Database:DefinitionsnRelational database:qa set of relations.nRelation:made up of 2 parts:qSchema:specifies name of relation,plus name and type of each column.nE.g.Students(sid:string,name:string,login:string,age:integer,gpa:real)qInstance:a table,with rows and columns.n#rows=cardinalityn#fields=arity(or degree)nCan think of a relation as a set of rows or tuples.qi.e.,all rows are distinctEx:Instance of Students Relationsid name login age gpa 53666 Jones jonescs 18 3.4 53688 Smith smithe ecs 18 3.2 53650 Smith smithmath 19 3.8 Cardinality=3,arity=5,all rows distinct Do all values in each column of a relation instance have to be distinct?SQL-A language for Relational DBsnSQL(a.k.a.“Sequel”),standard languagenData Definition Language(DDL)qcreate,modify,delete relationsqspecify constraintsqadminister users,security,etc.nData Manipulation Language(DML)qSpecify queries to find tuples that satisfy criteriaqadd,modify,remove tuplesSQL OverviewnCREATE TABLE (,)nINSERT INTO ()VALUES()nDELETE FROM WHERE nUPDATE SET =WHERE nSELECT FROM WHERE Creating Relations in SQLnCreates the Students relation.qNote:the type(domain)of each field is specified,and enforced by the DBMS whenever tuples are added or modified.CREATE TABLE Students(sid CHAR(20),name CHAR(20),login CHAR(10),age INTEGER,gpa FLOAT)Table Creation(Cont.)nAnother example:qthe Enrolled table holds information about courses students take.CREATE TABLE Enrolled(sid CHAR(20),cid CHAR(20),grade CHAR(2)Adding and Deleting TuplesnCan insert a single tuple using:INSERT INTO Students(sid,name,login,age,gpa)VALUES(53688,Smith,smithee,18,3.2)nCan delete all tuples satisfying some condition(e.g.,name=Smith):DELETE FROM Students SWHERE S.name=SmithPowerful variants of these commands are available;more later!KeysnKeys are a way to associate tuples in different relations.nKeys are one form of integrity constraint(IC)sidnameloginagegpa53666 Jones jonescs183.453688 Smith smitheecs183.253650 Smith smithmath193.8sidcidgrade53666 Carnatic101C53666 Reggae203B53650 Topology112A53666 History105BEnrolledStudentsPRIMARY KeyFOREIGN KeyPrimary KeysnA set of fields is a superkey if:qNo two distinct tuples can have same values in all key fieldsnA set of fields is a key for a relation if:qIt is a superkeyqNo subset of the fields is a superkey.(i.e.,minimal).nwhat if more than one keys for a relation?qOne of the keys is chosen(by DBA)to be the primary key.Other keys are called candidate keys.nE.g.qsid is a key for Students.qWhat about name?qThe set sid,gpa is a superkey.Primary and Candidate Keys in SQLnPossibly many candidate keys (specified using UNIQUE),one of which is chosen as the primary key.Keys must be used carefully!“For a given student and course,there is a single grade.”“Students can take only one course,and no two students in a course receive the same grade.”CREATE TABLE Enrolled (sid CHAR(20)cid CHAR(20),grade CHAR(2),PRIMARY KEY(sid,cid)CREATE TABLE Enrolled (sid CHAR(20),cid CHAR(20),grade CHAR(2),PRIMARY KEY (sid),UNIQUE(cid,grade)vs.Foreign Keys vs.Referential IntegritynForeign key:Set of fields in one relation that is used to refer to a tuple in another relation.qMust correspond to the primary key of the other relation.qLike a logical pointer.nIf all foreign key constraints are enforced,referential integrity is achieved(i.e.,no dangling references.)Foreign Keys in SQLnE.g.Only students listed in the Students relation should be allowed to enroll for courses.q sid is a foreign key referring to Students:CREATE TABLE Enrolled (sid CHAR(20),cid CHAR(20),grade CHAR(2),PRIMARY KEY(sid,cid),FOREIGN KEY(sid)REFERENCES Students)sidcidgrade53666 Carnatic101C53666 Reggae203B53650 Topology112A53666 History105BEnrolledsidnameloginagegpa53666 Jones jonescs183.453688 Smith smitheecs183.253650 Smith smithmath193.8Students11111 English102 AEnforcing Referential Integritynsid in Enrolled:foreign key referencing Students.nScenarios:qInsert Enrolled tuple with non-existent student id?qDelete a Students tuple?nAlso delete Enrolled tuples that refer to it?(Cascade)nDisallow if referred to?(No Action)nSet sid in referring Enrolled tuples to a default value?(Set Default)nSet sid in referring Enrolled tuples to null,denoting unknown or inapplicable.(Set NULL)nSimilar issues arise if primary key of Students tuple is updated.Integrity Constraints(ICs)nIC:condition that must be true for any instance of the databaseqe.g.,domain constraints.qICs are specified when schema is defined.qICs are checked when relations are modified.nA legal instance of a relation is one that satisfies all specified ICs.qDBMS should not allow illegal instances.nIf the DBMS checks ICs,stored data is more faithful to real-world meaning.qAvoids data entry errors,too!Where do ICs Come From?nSemantics of the real world!nKey and foreign key ICs are the most commonnMore general ICs supported too.Relational Query LanguagesnFeature:Simple,powerful ad hoc queryingnDeclarative languagesqQueries precisely specify what to returnqDBMS is responsible for efficient evaluation(how).qAllows the optimizer to extensively re-order operations,and still ensure that the answer does not change.nKey to data independence!The SQL Query LanguagenThe most widely used relational query language.qCurrent std is SQL:2008;SQL92 is a basic subsetnTo find all 18 year old students,we can write:SELECT*FROM Students S WHERE S.age=18 To find just names and logins,replace the first line:SELECT S.name,S.login sid name age gpa 53666 Jones 18 3.4 53688 Smith 18 3.2 53650 Smithlogin jonescs smithee smithmath 193.8 Querying Multiple RelationsnWhat does the following query compute?SELECT S.name,E.cid FROM Students S,Enrolled E WHERE S.sid=E.sid AND E.grade=Asidcidgrade53831 Carnatic101C53831 Reggae203B53650 Topology112A53666 History105BGiven the following instance of EnrolledS.nameE.cidSmithTopology112we get:Semantics of a QuerynA conceptual evaluation method for the previous query:1.do FROM clause:compute cross-product of Students and Enrolled2.do WHERE clause:Check conditions,discard tuples that fail3.do SELECT clause:Delete unwanted fieldsnRemember,this is conceptual.Actual evaluation will be much more efficient,but must produce the same answers.Cross-product of Students and Enrolled InstancesS.sid S.name S.login S.age S.gpa E.sid E.cid E.grade 53666 Jones jonescs 18 3.4 53831 Carnatic101 C 53666 Jones jonescs 18 3.4 53832 Reggae203 B 53666 Jones jonescs 18 3.4 53650 Topology112 A 53666 Jones jonescs 18 3.4 53666 History105 B 53688 Smith smithee 18 3.2 53831 Carnatic101 C 53688 Smith smithee 18 3.2 53831 Reggae203 B 53688 Smith smithee 18 3.2 53650 Topology112 A 53688 Smith smithee 18 3.2 53666 History105 B 53650 Smith smithmath 19 3.8 53831 Carnatic101 C 53650 Smith smithma th 19 3.8 53831 Reggae203 B 53650 Smith smithmath 19 3.8 53650 Topology112 A 53650 Smith smithmath 19 3.8 53666 History105 B Logical DB Design:ER to RelationalnEntity sets to tables.CREATE TABLE Employees (ssn CHAR(11),name CHAR(20),lot INTEGER,PRIMARY KEY (ssn)Employeesssnnamelotssnnamelot123-22-3666Attishoo48231-31-5368Smiley22131-24-3650Smethurst35Relationship Sets to TablesnIn translating a many-to-many relationship set to a relation,attributes of the relation must include:1)Keys for each participating entity set (as foreign keys).This set of attributes forms a superkey for the relation.2)All descriptive attributes.CREATE TABLE Works_In(ssn CHAR(1),did INTEGER,since DATE,PRIMARY KEY(ssn,did),FOREIGN KEY(ssn)REFERENCES Employees,FOREIGN KEY(did)REFERENCES Departments)ssndidsince123-22-3666511/1/91123-22-3666563/3/93231-31-5368512/2/92Review:Key ConstraintsnEach dept has at most one manager,according to the key constraint on Manages.Translation to relational model?Many-to-Many1-to-11-to ManyMany-to-1dnamebudgetdidsincelotnamessnManagesEmployeesDepartmentsTranslating ER Diagrams with Key ConstraintsReview:Participation ConstraintsnDoes every department have a manager?qIf so,this is a participation constraint:the participation of Departments in Manages is said to be total(vs.partial).nEvery did value in Departments table must appear in a row of the Manages table(with a non-null ssn value!)lotnamednamebudgetdidsincenamednamebudgetdidsinceManagessinceDepartmentsEmployeesssnWorks_InParticipation Constraints in SQLnWe can capture participation constraints involving one entity set in a binary relationship,but little else(without resorting to CHECK constraints).CREATE TABLE Dept_Mgr(did INTEGER,dname CHAR(20),budget REAL,ssn CHAR(11)NOT NULL,since DATE,PRIMARY KEY (did),FOREIGN KEY (ssn)REFERENCES Employees,ON DELETE NO ACTION)Review:Weak EntitiesnA weak entity can be identified uniquely only by considering the primary key of another(owner)entity.qOwner entity set and weak entity set must participate in a one-to-many relationship set(1 owner,many weak entities).qWeak entity set must have total participation in this identifying relationship set.lotnameagepnameDependentsEmployeesssnPolicycostTranslating Weak Entity SetsnWeak entity set and identifying relationship set are translated into a single table.qWhen the owner entity is deleted,all owned weak entities must also be deleted.CREATE TABLE Dep_Policy(pname CHAR(20),age INTEGER,cost REAL,ssn CHAR(11)NOT NULL,PRIMARY KEY (pname,ssn),FOREIGN KEY (ssn)REFERENCES Employees,ON DELETE CASCADE)Relational Model:SummarynA tabular representation of data,simple and intuitive,currently the most widely usedqObject-relational features in most productsnIntegrity constraints can be specified by the DBA,based on application semantics.DBMS checks for violations.qTwo important ICs:primary and foreign keysqIn addition,we always have domain constraints.nPowerful query languages exist.qSQL is the standard commercial onenDDL-Data Definition LanguagenDML-Data Manipulation Language
收藏