1 relations rosen 5 th ed., ch. 7. 2 relations relationships between elements of sets occur very...

42
1 Relations Rosen 5 Rosen 5 th th ed., ch. 7 ed., ch. 7

Post on 20-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

1

Relations

Rosen 5Rosen 5thth ed., ch. 7 ed., ch. 7

2

Relations

• Relationships between elements of sets occur Relationships between elements of sets occur very often.very often.– (Employee, Salary)(Employee, Salary)– (Students, Courses, GPA)(Students, Courses, GPA)

• We use ordered pairs (or We use ordered pairs (or n-tuplesn-tuples) of elements ) of elements from the sets to represent relationships. from the sets to represent relationships.

3

Binary Relations

• A A binary relationbinary relation RR from set from set AA to set to set BB, written , written RR::AA↔↔BB, is a subset of , is a subset of AA××BB. . – E.g.E.g., let , let << : : NN↔↔NN :≡ {( :≡ {(nn,,mm)) | | n n < < mm}}

• The notation The notation aRbaRb means ( means (aa,,bb))R.R.– E.g.E.g., , a a << bb means ( means (aa,,bb)) <<

• If If aRbaRb we may say we may say

“ “aa is related to is related to bb (by relation (by relation RR)”)”

4

Example

A: {students at UNR}, B: {courses offered at UNR}A: {students at UNR}, B: {courses offered at UNR}

R: “relation of students enrolled in courses”R: “relation of students enrolled in courses”

(Jason, CS365), (Mary, CS201) (Jason, CS365), (Mary, CS201) are inare in R R

If Mary does not take CS365, then (Mary, CS365) If Mary does not take CS365, then (Mary, CS365) is notis not in R! in R!

If CS480 is not being offered, then (Jason, CS480), (Mary, If CS480 is not being offered, then (Jason, CS480), (Mary, CS480) CS480) are notare not in R! in R!

5

Complementary Relations

• Let Let RR::AA↔↔BB be any binary relation. be any binary relation.• Then, Then, RR::AA↔↔BB, the , the complementcomplement of of RR, is the , is the

binary relation defined bybinary relation defined byRR :≡ {( :≡ {(aa,,bb) | () | (aa,,bb))RR} = (} = (AA××BB) − ) − RR

Note this is just Note this is just RR if the universe of if the universe of discourse is discourse is UU = = AA××BB; thus the name ; thus the name complement.complement.

• Note the complement of Note the complement of RR is is RR..Example: < = {(a,b) | (a,b)<<} = {(} = {(aa,,bb) | ) | ¬¬aa<<bb} = } = ≥≥

6

Inverse Relations

• Any binary relation Any binary relation RR::AA↔↔BB has an has an inverseinverse relation relation RR−1−1::BB↔↔AA, defined by, defined by

RR−1 −1 :≡ {(:≡ {(bb,,aa) | () | (aa,,bb))RR}.}.

E.g.E.g., , <<−1−1 = {( = {(bb,,aa) | ) | aa<<bb} = {(} = {(bb,,aa) | ) | bb>>aa} = } = >>..

7

Functions as Relations

• A function f:AA function f:AB is a relation from A to BB is a relation from A to B• A relation from A to B is not always a function A relation from A to B is not always a function

f:Af:AB (e.g., relations could be one-to-many)B (e.g., relations could be one-to-many)• Relations are generalizations of functions!Relations are generalizations of functions!

8

Relations on a Set

• A (binary) relation from a set A (binary) relation from a set AA to itself is called to itself is called a relation a relation onon the set the set AA..

A: {1,2,3,4}

R={(a,b) | a divides b}

9

Example

How many relations are there on a set A with How many relations are there on a set A with nn elements?elements?

10

Reflexivity

• A relation A relation RR on on AA is is reflexivereflexive if if aaAA, , aRaaRa..– E.g.E.g., the relation , the relation ≥≥ :≡ {( :≡ {(aa,,bb) | ) | aa≥≥bb} is reflexive.} is reflexive.– Is the “divide” relation on the set of positive Is the “divide” relation on the set of positive

integers reflexive?integers reflexive?

11

Symmetry & Antisymmetry

• A binary relation A binary relation RR on on AA is symmetric iff is symmetric iff RR = = RR−1−1, that is, if (, that is, if (aa,,bb))RR ↔ ( ↔ (bb,,aa))RR..– E.g.E.g., , == (equality) is symmetric. (equality) is symmetric. << is not. is not.– ““is married to” is symmetric, “likes” is not.is married to” is symmetric, “likes” is not.

• A binary relation A binary relation RR is is antisymmetricantisymmetric if if ((aa,,bb))RR → ( → (bb,,aa))RR..– << is antisymmetric, “likes” is not. is antisymmetric, “likes” is not.

12

Transitivity

• A relation A relation RR is is transitivetransitive iff (for all iff (for all aa,,bb,,cc))((aa,,bb))RR ( (bb,,cc))RR → ( → (aa,,cc))RR..

• Examples: Examples:

• ““is an ancestor of” is transitive.is an ancestor of” is transitive.

• Is the “divides” relation on the set of Is the “divides” relation on the set of positive integers transitive?positive integers transitive?

13

Combining Relations

• Two relations can be combined in a similar Two relations can be combined in a similar way to combining two sets.way to combining two sets.

1 2

1 2

1 2

2 1

R R

R R

R R

R R

14

Composite Relations

• Let Let RR::AA↔↔BB, and , and SS::BB↔↔CC. Then the . Then the compositecomposite SSRR of of RR and and SS is defined as: is defined as:

SSR R = {(= {(aa,,cc) | ) | aRbaRb bScbSc}}• Function composition Function composition ffgg is an example. is an example.• The The nnthth power power RRnn of a relation of a relation RR on a set on a set AA

can be defined recursively by:can be defined recursively by:

RR11 :≡ R :≡ R ;; RRnn+1 +1 :≡ :≡ RRnnRR for all for all nn≥0.≥0.

15

Example

R is a relation from {1,2,3} to {1,2,3,4}R is a relation from {1,2,3} to {1,2,3,4}

R ={(1,1),(1,4),(2,3),(3,1),(3,4)}R ={(1,1),(1,4),(2,3),(3,1),(3,4)}

S is a relation from {1,2,3,4} to {0,1,2}S is a relation from {1,2,3,4} to {0,1,2}

S = {(1,0),(2,0),(3,1),(3,2),(4,1)}S = {(1,0),(2,0),(3,1),(3,2),(4,1)}

RRS = S = {(1,0),(1,1),(2,1),(2,2),(3,0),(3,1)}{(1,0),(1,1),(2,1),(2,2),(3,0),(3,1)}

16

§7.2: n-ary Relations

• An An nn-ary relation -ary relation RR on sets on sets AA11,…,,…,AAnn, ,

written written RR::AA11,…,,…,AAnn, is a subset, is a subset

R R AA11× … × × … × AAnn..

• The The degreedegree of of RR is is nn..

• Example: R consists of 5-tuples (A,N,S,D,T)Example: R consists of 5-tuples (A,N,S,D,T) A: airplane flights, N: flight number, A: airplane flights, N: flight number,

S: starting point, D: destination, T: departure timeS: starting point, D: destination, T: departure time

17

Databases

• The time required to manipulate information in a The time required to manipulate information in a

database depends in how this information is stored.database depends in how this information is stored. • OperationsOperations: add/delete, update, search, combine etc.: add/delete, update, search, combine etc.• Various methods for representing databases have Various methods for representing databases have

been developed.been developed.• We will discuss the “We will discuss the “relational modelrelational model”.”.

18

Relational Databases

• A database consists of A database consists of recordsrecords, , which are which are n-tuplesn-tuples, made up of , made up of fieldsfields..

• A A relational databaserelational database represents records as an represents records as an n-aryn-ary relation relation RR..

(STUDENT_NAME, ID, (STUDENT_NAME, ID, MAJOR, GPA)MAJOR, GPA)

• Relations are also called Relations are also called “tables” (e.g., displayed as “tables” (e.g., displayed as tables often)tables often)

19

Relational Databases

• A domain A domain AAii of an of an n-aryn-ary relation is called relation is called

primary keyprimary key when no two when no two n-tuples n-tuples have the have the same value on this domain (e.g., ID) same value on this domain (e.g., ID)

• A A composite keycomposite key is a subset of domains { is a subset of domains {AAii, ,

AAjj,, … …} such that an n-tuple (…,} such that an n-tuple (…,aaii,…,,…,aajj,…) is ,…) is

determined uniquely for each composite determined uniquely for each composite value (value (aaii, , aajj,…),…)AAii××AAjj×… ×…

20

Selection Operator

• Let R be an n-ary relation and C a condition Let R be an n-ary relation and C a condition that elements in R may satisfy.that elements in R may satisfy.

• The The selection operatorselection operator ssCC maps any ( maps any (n-aryn-ary) )

relation relation RR on on AA to the to the n-ary n-ary relation of all relation of all n-n-tuplestuples from from RR that satisfy that satisfy C. C.

21

Example

• Suppose we have a domain Suppose we have a domain A A = StudentName × Standing × SocSecNos= StudentName × Standing × SocSecNos

• Suppose we define a certain condition on Suppose we define a certain condition on AA, , UpperLevelUpperLevel((namename,,standingstanding,,ssnssn) :≡ ) :≡ [([(standing = standing = junior)junior) ( (standingstanding = senior)] = senior)]

• Then, Then, ssUpperLevelUpperLevel is the selection operator that takes is the selection operator that takes any relation any relation RR on on AA (database of students) and (database of students) and produces a relation consisting of produces a relation consisting of justjust the upper- the upper-level classes (juniors and seniors).level classes (juniors and seniors).

22

Projection Operators

• The projection operator maps the The projection operator maps the

n-tuplen-tuple

to the to the m-tuplem-tuple

• In other words, it deletes In other words, it deletes n-mn-m of the components of the components of an of an n-tuplen-tuple. .

1 2 ... mi i iP1( ,..., )na a

1( ,..., )

mi ia a

23

Example

Note that fewer rows may result when a projection is applied !Note that fewer rows may result when a projection is applied !

24

More Examples

• Suppose we have a ternary (3-ary) domain Suppose we have a ternary (3-ary) domain CarsCars==ModelModel××YearYear××Color. Color. (note (note nn=3).=3).

• Consider the index sequence {Consider the index sequence {iikk}= 1,3. (}= 1,3. (mm=2)=2)• Then the projection Then the projection P P simply maps each tuple simply maps each tuple

((aa11,,aa22,,aa33) = () = (modelmodel,,yearyear,,colorcolor) to its image: ) to its image:

• This operator can be usefully applied to a whole This operator can be usefully applied to a whole relation relation RRCarsCars (database of cars) to obtain a list (database of cars) to obtain a list of model/color combinations available.of model/color combinations available.

{ik}

),(),(),( 3121colormodelaaaa ii

25

Join Operator

• Puts two relations together to form a sort of Puts two relations together to form a sort of combined relation.combined relation.

• If the tuple (If the tuple (AA,,BB) appears in ) appears in RR11, and the , and the

tuple (tuple (BB,,CC) appears in ) appears in RR22, then the tuple , then the tuple

((AA,,BB,,CC) appears in the join ) appears in the join JJ((RR11,,RR22).).

– AA, , BB, , CC can also be sequences of elements can also be sequences of elements rather than single elements.rather than single elements.

26

Example

27

Join Example

• Suppose Suppose RR11 is a teaching assignment table, is a teaching assignment table,

relating relating ProfessorsProfessors to to CoursesCourses. .

• Suppose Suppose RR22 is a room assignment table is a room assignment table

relating relating CoursesCourses to to RoomsRooms,,TimesTimes..

• Then Then JJ((RR11,,RR22) is like your class schedule, ) is like your class schedule,

listing (listing (professorprofessor,,coursecourse,,roomroom,,timetime).).

28

SQL Example

SELECT SELECT Departure_TimeDeparture_Time FROM FROM FlightsFlights WHERE WHERE destination=“Detroit”destination=“Detroit”

Find projection P5 of the selection of 5-tuples that satisfy Find projection P5 of the selection of 5-tuples that satisfy the constraint “destination=Detroit”the constraint “destination=Detroit”

29

§7.3: Representing Relations

• Some ways to represent Some ways to represent nn-ary relations:-ary relations:– With an explicit list or table of its tuples.With an explicit list or table of its tuples.– With a function from the domain to {With a function from the domain to {TT,,FF}.}.

• Or with an algorithm for computing this function.Or with an algorithm for computing this function.

• Some special ways to represent binary Some special ways to represent binary relations:relations:– With a zero-one matrix.With a zero-one matrix.– With a directed graph.With a directed graph.

30

Using Zero-One Matrices

• To represent a relation To represent a relation RR by a matrix by a matrix MMRR = [ = [mmijij], let ], let mmijij = 1 if ( = 1 if (aaii,,bbjj))RR, else 0., else 0.

• E.g.E.g., Joe likes Susan and Mary, Fred likes , Joe likes Susan and Mary, Fred likes Mary, and Mark likes Sally.Mary, and Mark likes Sally.

• The 0-1 matrix The 0-1 matrix representationrepresentationof that “Likes”of that “Likes”relation:relation:

1 00

010

0 1 1

Mark

Fred

JoeSallyMarySusan

31

Zero-One Reflexive, Symmetric

• Terms:Terms: Reflexive Reflexive,, non-Reflexive non-Reflexive, s, symmetric, ymmetric, and antisymmetricand antisymmetric..– These relation characteristics are very easy to These relation characteristics are very easy to

recognize by inspection of the zero-one matrix.recognize by inspection of the zero-one matrix.

1 0 1 0

1 1 1 0 1 1

1 0

1 1 0 0

Reflexive:all 1’s on diagonal

Non-reflexive:some 0’s on diagonal

Symmetric:all identical

across diagonal

Antisymmetric:all 1’s are across

from 0’s

any-thing

any-thing

any-thing

any-thing

anything

anything

32

Using Directed Graphs

• A A directed graphdirected graph or or digraphdigraph GG=(=(VVGG,,EEGG) is a set ) is a set VVGG of of

vertices (nodes)vertices (nodes) with a set with a set EEGGVVGG××VVGG of of edges edges

(arcs,links)(arcs,links). Visually represented using dots for nodes, . Visually represented using dots for nodes, and arrows for edges. Notice that a relation and arrows for edges. Notice that a relation RR::AA↔↔BB can be can be represented as a graph represented as a graph GGRR=(=(VVGG==AABB, , EEGG==RR).).

1 00

010

0 1 1

Mark

Fred

JoeSallyMarySusanMR

GR

Joe

Fred

Mark

Susan

Mary

Sally

Node set VG

(black dots)

Edge set EG

(blue arrows)

33

Digraph Reflexive, Symmetric

It is extremely easy to recognize the reflexive/irreflexive/ It is extremely easy to recognize the reflexive/irreflexive/ symmetric/antisymmetric properties by graph inspection.symmetric/antisymmetric properties by graph inspection.

Reflexive:Every node

has a self-loop

Irreflexive:No node

links to itself

Symmetric:Every link isbidirectional

Antisymmetric:

No link isbidirectional

Asymmetric, non-antisymmetric Non-reflexive, non-irreflexive

34

§7.4: Closures of Relations

• For any property For any property XX, the “, the “XX closure” of a set closure” of a set AA is defined as is defined as the “smallest” superset of the “smallest” superset of AA that has the given property. that has the given property.

• The The reflexive closurereflexive closure of a relation of a relation RR on on A A is obtained by is obtained by adding (adding (aa,,aa) to ) to RR for each for each aaAA. . I.e.I.e.,, it is it is RR IIAA

• The The symmetric closuresymmetric closure of of RR is obtained by adding ( is obtained by adding (bb,,aa) to ) to RR for each ( for each (aa,,bb) in ) in RR. . I.e.I.e., it is , it is RR RR−1−1

• The The transitive closuretransitive closure or or connectivity relation connectivity relation of of RR is is obtained by repeatedly adding (obtained by repeatedly adding (aa,,cc) to ) to RR for each ( for each (aa,,bb),),((bb,,cc) in ) in RR..– I.e.I.e., it is, it is

Zn

nRR*

35

Paths in Digraphs/Binary Relations

• A A pathpath of length of length n n from node from node aa to to bb in the directed in the directed graph graph GG (or the binary relation (or the binary relation RR) is a sequence ) is a sequence ((aa,,xx11), (), (xx11,,xx22), …, (), …, (xxnn−1−1,,bb) of ) of nn ordered pairs in ordered pairs in EEGG (or (or RR).).– An empty sequence of edges is considered a path of An empty sequence of edges is considered a path of

length 0 from length 0 from aa to to aa..– If any path from If any path from aa to to bb exists, then we say that exists, then we say that aa is is

connected toconnected to bb. (“You can get there from here. (“You can get there from here.”).”)• A path of length A path of length nn≥1 from ≥1 from aa to to aa is called a is called a circuitcircuit

or a cycle.or a cycle.• Note that there exists a path of length Note that there exists a path of length nn from from aa to to

bb in in RR if and only if ( if and only if (aa,,bb))RRnn..

36

Simple Transitive Closure Alg.

A procedure to compute A procedure to compute RR** with 0-1 matrices. with 0-1 matrices.

procedureprocedure transClosuretransClosure((MMRR:rank:rank-n-n 0-1 mat.) 0-1 mat.)

AA := := BB := := MMRR;;

forfor ii := 2 to := 2 to nn beginbeginAA := := AA⊙MR; B := B A {join}

endreturn B {Alg. takes Θ(n4) time}

{note A represents Ri}

37

Roy-Warshall Algorithm

• Uses only Uses only ΘΘ((nn33) operations!) operations!

Procedure Procedure WarshallWarshall((MMRR : rank- : rank-nn 0-1 matrix) 0-1 matrix)

WW := := MMRR

forfor kk := 1 := 1 toto nnforfor ii := 1 := 1 toto nn

forfor jj := 1 := 1 toto nnwwijij := := wwijij ( (wwikik wwkjkj))

return Wreturn W {this represents {this represents RR**}}wij = 1 means there is a path from i to j going only through nodes ≤k

38

§7.5: Equivalence Relations

• An An equivalence relationequivalence relation (e.r.) on a set (e.r.) on a set AA is is simply any binary relation on simply any binary relation on AA that is that is reflexive, symmetric, and transitive.reflexive, symmetric, and transitive.– E.g.E.g., , == itself is an equivalence relation. itself is an equivalence relation.– For any function For any function ff::A→BA→B, the relation “have the , the relation “have the

same same ff value”, or value”, or ==ff :≡ {( :≡ {(aa11,,aa22) | ) | ff((aa11)=)=ff((aa22)} )}

is an equivalence relation, is an equivalence relation, e.g.e.g., let , let m=“m=“mother mother of” then of” then ==mm = “have the same mother” is an e.r. = “have the same mother” is an e.r.

39

Equivalence Relation Examples

• ““Strings Strings aa and and bb are the same length.” are the same length.”

• ““Integers Integers aa and and bb have the same absolute have the same absolute value.”value.”

• ““Real numbers Real numbers aa and and bb have the same have the same fractional part (fractional part (i.e.i.e., , aa − − bb ZZ).”).”

40

Equivalence Classes

• Let Let RR be any equiv. rel. on a set be any equiv. rel. on a set AA..• The The equivalence classequivalence class of of aa,,

[[aa]]RR :≡ { :≡ { bb | | aRbaRb } } (optional subscript (optional subscript RR))– It is the set of all elements of It is the set of all elements of AA that are “equivalent” to that are “equivalent” to

aa according to the eq.rel. according to the eq.rel. RR..– Each such Each such bb (including (including aa itself) is called a itself) is called a

representativerepresentative of [ of [aa]]RR..

• Since Since ff((aa)=[)=[aa]]RR is a function of is a function of aa, any equivalence , any equivalence relation relation R R be defined using be defined using aRbaRb :≡ “ :≡ “aa and and bb have have the same the same ff value”, given that value”, given that ff..

41

Equivalence Class Examples

• ““Strings Strings aa and and bb are the same length.” are the same length.”– [[aa] = the set of all strings of the same length as ] = the set of all strings of the same length as a.a.

• ““Integers Integers aa and and bb have the same absolute value.” have the same absolute value.”– [[aa] = the set {] = the set {aa, −, −aa}}

• ““Real numbers Real numbers aa and and bb have the same fractional have the same fractional part (part (i.e.i.e., , aa − − bb ZZ).”).”– [[aa] = the set {…, ] = the set {…, aa−2, −2, aa−1, −1, aa, , aa+1, +1, aa+2, …}+2, …}

42

Partitions

• A A partitionpartition of a set of a set AA is the set of all the is the set of all the equivalence classes {equivalence classes {AA11, , AA22, … } for some , … } for some

e.r. on e.r. on AA..

• The The AAii’s are all disjoint and their union = ’s are all disjoint and their union = AA..

• They “partition” the set into pieces. Within They “partition” the set into pieces. Within each piece, all members of the set are each piece, all members of the set are equivalent to each other.equivalent to each other.