Está en la página 1de 72

Algebra Relacional y Cálculo

Relacional

Bases de Datos I
René F. Navarro

© Pearson Education Limited 1995, 2005


Introducción
 El algebra y cálculo relacional son lenguajes formales asociados con el
modelo relacional.
 Informalmente, el algebra relacional es un lenguaje (de alto nivel)
procedural y el cálculo relacional es un lenguaje no procedural.
 Formalmente son equivalentes entre sí.
 Un lenguaje capaz de producir cualquier relación posible mediante el
calculo relacional se denomina relacionalmente completo.

2
© Pearson Education Limited 1995, 2005
Algebra relacional
 Las operaciones de algebra relacional se aplican a una o más
relaciones para definir otra relación sin modificar las relaciones
originales.

 Tanto los operandos como los resultados son relaciones, así la salida
de una operación puede convertirse en la entrada de otra operación.

 Esto permite combinar y anidar expresiones, como en aritmética. A


esta propiedad se denomina cierre (cerradura/closure).

3
© Pearson Education Limited 1995, 2005
Algebra relacional
 Cinco operaciones básicas:
◼ Selección,
◼ Proyección,
◼ Producto cartesiano,
◼ Unión, intersección y diferencia de conjuntos.
 Permiten realizar la mayoría de las operaciones de extracción de datos
necesarias.
 Las operaciones de combinación (join), intersección y división, que se
pueden expresar en término de las operaciones básicas.

4
© Pearson Education Limited 1995, 2005
Operaciones algebra relacional

5
© Pearson Education Limited 1995, 2005
Operaciones algebra relacional

6
© Pearson Education Limited 1995, 2005
7
8
9
10
Selección (Restricción)

 predicado (R)
◼ Se aplica a una relación R y genera otra relación que
contiene únicamente aquellas tuplas de R que satisfacen la
condición (predicado) especificada.

11
© Pearson Education Limited 1995, 2005
Ejemplo de selección
 ¿Empleados con salario superior a $10,000?
 salary > 10000 (Staff)

12
© Pearson Education Limited 1995, 2005
 salary > 10000 (Staff)

13
© Pearson Education Limited 1995, 2005
Proyección
 a1, . . . , an(R)
◼ La operación se aplica a una relación R y genera un
subconjunto vertical (columnas) de R, extrayendo los
valores de los atributos especificados y eliminando los
duplicados.

14
© Pearson Education Limited 1995, 2005
Ejemplo proyección
 Generar una lista de salarios para todo el personal mostrando
solamente los detalles de staffNo, fName, lName, y salary.
 staffNo, fName, lName, salary (Staff)

15

© Pearson Education Limited 1995, 2005


Unión
RS
◼ La unión de las relaciones R y S define una relación que contiene
todas las tuplas de R, de S o tanto de R como de S, eliminándose
las tuplas duplicadas.
◼ R y S deben ser compatibles con respecto a la unión.

 Si R y S tiene I y J tuplas, respectivamente, su unión se


obtiene concatenándolas en una única relación con un
máximo de (I + J) tuplas.
16
© Pearson Education Limited 1995, 2005
Ejemplo unión
 Listar todas las ciudades en las que exista una sucursal o
un inmueble de alquiler.
city(Branch)  city(PropertyForRent)

17
© Pearson Education Limited 1995, 2005
Ejemplo unión

18
Diferencia de conjuntos
R–S
◼ La operación de diferencia de conjuntos define una relación
compuesta por las tuplas que se encuentran en la relación R, pero
no en S.
◼ R y S deben ser compatibles con respecto a la unión.

19
© Pearson Education Limited 1995, 2005
Ejemplo diferencia de conjuntos
 Listar todas las ciudades en las que exista un sucursal,
pero no haya inmuebles de alquiler.
 city (Branch) –  city (PropertyForRent)

20
© Pearson Education Limited 1995, 2005
Intersección
R  S
◼ Define una relación que consiste en el conjunto de todas
las tuplas que están tanto en R como en S.
◼ R y S deben ser compatibles con respecto a la unión.
 Expresada en operaciones básicas:
◼ R  S = R – (R – S)

21
© Pearson Education Limited 1995, 2005
Ejemplo
 Enumerar todas las ciudades en las que exista tanto una sucursal
como al menos un inmueble en alquiler.

 city (Branch)   city (PropertyForRent)

22
© Pearson Education Limited 1995, 2005
Producto Cartesiano
RXS
◼ Define una operación que es la concatenación de cada tupla de la
relación R con cada tupla de la relación S.

23
© Pearson Education Limited 1995, 2005
Producto cartesiano
 Enumerar los nombres y comentarios de todos los clientes que hayan
visto un inmueble de alquiler.

( clientNo, fName, lName (Client)) X ( clientNo, propertyNo, comment (Viewing))

24
© Pearson Education Limited 1995, 2005
Producto cartesiano

25
© Pearson Education Limited 1995, 2005
Producto cartesiano
 Enumerar los nombres y comentarios de todos los clientes que hayan
visto un inmueble de alquiler.
(clientNo, fName, lName(Client)) X (clientNo, propertyNo, comment (Viewing))
clientNo, fName, lName(Client)
CR76 John Kay
CR56 Aline Steward
CR74 Mike Ritchie
CR62 Mary Tregear clientNo, propertyNo, comment (Viewing)
CR56 PA14 too small
CR76 PG4 too remote
CR56 PG4 null
CR62 PA14 no dining room
CR56 PG36 null
26
© Pearson Education Limited 1995, 2005
( clientNo, fName, lName(Client)) X ( clientNo, propertyNo, comment (Viewing))

CR76 John Kay CR56 PA14 too small


CR76 John Kay CR76 PG4 too remote
CR76 John Kay CR56 PG4 null
CR76 John Kay CR62 PA14 no dining room
CR76 John Kay CR56 PG36 null
CR56 Aline Steward CR56 PA14 too small
CR56 Aline Steward CR76 PG4 too remote
CR56 Aline Steward CR56 PG4 null
CR56 Aline Steward CR62 PA14 no dining room
CR56 Aline Steward CR56 PG36 null
CR74 Mike Ritchie CR56 PA14 too small
CR74 Mike Ritchie CR76 PG4 too remote
CR74 Mike Ritchie CR56 PG4 null
CR74 Mike Ritchie CR62 PA14 no dining room
CR74 Mike Ritchie CR56 PG36 null
CR62 Mary Tregear CR56 PA14 too small
CR62 Mary Tregear CR76 PG4 too remote
CR62 Mary Tregear CR56 PG4 null
CR62 Mary Tregear CR62 PA14 no dining room 27
CR62 Mary Tregear CR56 PG36 null
( clientNo, fName, lName(Client)) X ( clientNo, propertyNo, comment (Viewing))

CR76 John Kay CR56 PA14 too small


CR76 John Kay CR76 PG4 too remote
CR76 John Kay CR56 PG4 null
CR76 John Kay CR62 PA14 no dining room
CR76 John Kay CR56 PG36 null
CR56 Aline Steward CR56 PA14 too small
CR56 Aline Steward CR76 PG4 too remote
CR56 Aline Steward CR56 PG4 null
CR56 Aline Steward CR62 PA14 no dining room
CR56 Aline Steward CR56 PG36 null
CR74 Mike Ritchie CR56 PA14 too small
CR74 Mike Ritchie CR76 PG4 too remote
CR74 Mike Ritchie CR56 PG4 null
CR74 Mike Ritchie CR62 PA14 no dining room
CR74 Mike Ritchie CR56 PG36 null
CR62 Mary Tregear CR56 PA14 too small
CR62 Mary Tregear CR76 PG4 too remote
CR62 Mary Tregear CR56 PG4 null
CR62 Mary Tregear CR62 PA14 no dining room 28
CR62 Mary Tregear CR56 PG36 null
Producto Cartesiano + Selección
 Usar la operación de selección para extraer aquellas tuplas donde
Client.clientNo = Viewing.clientNo.
Client.clientNo = Viewing.clientNo((clientNo, fName, lName(Client))  (clientNo, propertyNo, comment(Viewing)))

El producto Cartesiano y la selección se pueden representar


como una sola operación de combinación (Join).
29
© Pearson Education Limited 1995, 2005
Join Operations
 El join (Combinación) se deriva del producto Cartesiano.

 Equivalente a realizar una Selección, empleando un predicado de


combinación como fórmula de selección sobre el producto Cartesiano de
dos relaciones.

 Una de las operaciones más difíciles de implementar eficientemente en un


SMBDR y una de las razones porque un SMBDR tiene problemas
intrínsecos de desempeño.

30
© Pearson Education Limited 1995, 2005
Tipos de Join
 Diferentes formas de la operación join
◼ Theta join
◼ Equijoin (tipo particular de Theta join)
◼ Natural join
◼ Outer join
◼ Semijoin

31
© Pearson Education Limited 1995, 2005
Theta join (-join)
R FS
◼ Define una relación que contiene tuplas que satisfacen el predicado
F, del producto Cartesiano de R y S.
◼ El predicado F es de la forma R.ai  S.bi donde  puede ser un
operador de comparación (<, , >, , =, ).

32
© Pearson Education Limited 1995, 2005
Theta join (-join)
 Se puede reescribir la operación Theta join usando operaciones
básicas como:

R FS = F(R  S)

El grado del resultado es la suma de los grados de los


operando R y S. Si el predicado F contiene únicamente
igualdad (=), se usa el término Equijoin.

33
© Pearson Education Limited 1995, 2005
Example - Equijoin
 Nombres y comentarios de todos los clientes que
han visitado propiedades.
(clientNo, fName, lName(Client)) Client.clientNo =
Viewing.clientNo (clientNo, propertyNo, comment(Viewing))

34
© Pearson Education Limited 1995, 2005
Natural join
R S
◼ Equijoin de dos relaciones R y S sobre todos los atributos
comunes x. Una ocurrencia de cada atributo común se
elimina del resultado.

35
© Pearson Education Limited 1995, 2005
Example - Natural join
 Nombres y comentarios de todos los clientes que han visitado
propiedades.
(clientNo, fName, lName(Client))
(clientNo, propertyNo, comment(Viewing))

36
© Pearson Education Limited 1995, 2005
Outer join
 Para mostrar tuplas que no tienen valores que empaten en la
columna join se emplea el Outer join.

R S
◼ (Left) outer join es una combinación en la que tambien se incluyen en
la relación resultante las tuplas de R que no tengan valores
correspondientes en los atributos comunes de S. A los valores no
existentes en la relación S se le asigna un valor nulo.

37
© Pearson Education Limited 1995, 2005
Example - Left Outer join
 Reporte de estado de propiedades visitadas.
propertyNo, street, city(PropertyForRent)
Viewing

38
© Pearson Education Limited 1995, 2005
Semijoin
R FS
◼ Define una relación que contiene las tuplas de R que participan en la
combinación de R con S.

Equivalente a usar una proyección y combinación:

R FS = A(R F S)

39
© Pearson Education Limited 1995, 2005
Example - Semijoin
 Mostrar todo los detalles del staff que trabaje en una sucursal de
Glasgow.
Staff Staff.branchNo=Branch.branchNo(city=‘Glasgow’(Branch))

40
© Pearson Education Limited 1995, 2005
División R  S
R  S
◼ Define una relación sobre los atributos C que esta compuesta por el conjunto de
tuplas de R que se corresponden con la combinación de todas la tuplas de S.
◼ C es el conjunto de atributos de R que no están en S.

 Se expresa en operaciones básicas:


T1  C(R)
T2  C((T1 X S ) – R)
R  S  T1 – T2

41
© Pearson Education Limited 1995, 2005
Ejemplo - División
 Identificar todos los clientes que hayan visto todos los inmuebles
con tres habitaciones.
(clientNo, propertyNo(Viewing)) 
(propertyNo(rooms = 3 (PropertyForRent)))

42
© Pearson Education Limited 1995, 2005
Division
R( A, B ) S( B ) Q( A )
a1 b1 b1 ➔ a2
a1 b2 b2
a2 b1 b3
a2 b2
a2 b3
a2 b4
a3 b1
a3 b3
43
División R  S
R S
R.a R.b
S.b
a1 b1
b1
a1 b2
b2
a2 b1
b3
a2 b2
a2 b3
a2 b4
a3 b1
a3 b3

44
División R  S
R S T1  C(R)
R.a R.b S.b
a1 b1 R.a
b1
a1 b2 a1
b2
a2 b1 a2
b3
a2 b2 a3
a2 b3
a2 b4
a3 b1
a3 b3

45
División R  S
T1  C(R) T2  C((T1 X S ) – R) = a1
a3
R.a R.a S.b
a1 a1 b1
a2 a1 b2 (T1 X S ) – R
a3 a1 b3 R.a S.b
a2 b1 a1 b3
T1 X S =
a2 b2 a3 b2
a2 b3
a3 b1
a3 b2
a3 b3
46
División R  S
T1  C(R) R.a
T2  C((T1 X S ) – R) = a1
R.a a3
a1
a2 R  S  T1 – T2
a3
R.a
a2

47
Operaciones para agrupar
 GAAL(R)
◼ Agrupa las tuplas de la relación R según los atributos agrupación, GA, y
luego aplica la lista de funciones de agregación AL para definir una
nueva relación.
◼ AL contiene una más parejas (<función_agregación>, <atributo>).
◼ La relación resultante contiene los atributos de agrupación, GA, junto
con los resultados de cada una de las funciones de agregación.

48
© Pearson Education Limited 1995, 2005
Operaciones de agregacion
 AL(R)
◼ Aplica la lista de funciones de agregación, AL, a la relación R para
definir una relación sobre la lista de agregación.
◼ AL contiene una más parejas (<función_agregación>, <atributo>).
 Principales funciones de agregación: COUNT, SUM, AVG,
MIN, and MAX.

49
© Pearson Education Limited 1995, 2005
Example – Aggregate Operations
 Cuantas propiedades tiene más de £350 de renta
mensual?
R(myCount) COUNT propertyNo (σrent > 350 (PropertyForRent))

50
© Pearson Education Limited 1995, 2005
Example – Grouping Operation
 Calcular el número de empleado que trabajan
en cada sucursal y la suma de salarios.
R(branchNo, myCount, mySum)
branchNo  COUNT staffNo, SUM salary (Staff)

51
© Pearson Education Limited 1995, 2005
52
Relational Calculus
 Relational calculus query specifies what is to be retrieved rather than how
to retrieve it.
◼ No description of how to evaluate a query.

 In first-order logic (or predicate calculus), predicate is a truth-valued


function with arguments.
 When we substitute values for the arguments, function yields an
expression, called a proposition, which can be either true or false.

53
© Pearson Education Limited 1995, 2005
Relational Calculus
 If predicate contains a variable (e.g. ‘x is a member of staff’),
there must be a range for x.
 When we substitute some values of this range for x, proposition
may be true; for other values, it may be false.
 When applied to databases, relational calculus has forms: tuple
and domain.

54
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Interested in finding tuples for which a predicate is
true. Based on use of tuple variables.
 Tuple variable is a variable that ‘ranges over’ a named
relation: i.e. variable whose only permitted values are
tuples of the relation.
 Specify range of a tuple variable S as the Staff relation
as:
Staff(S)
 To find set of all tuples S such that P(S) is true:
{S | P(S)}
55
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus - Example
 To find details of all staff earning more than £10,000:
{S | Staff(S)  S.salary > 10000}

 To find a particular attribute, such as salary, write:


{S.salary | Staff(S)  S.salary > 10000}

56
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Can use two quantifiers to tell how many instances the predicate
applies to:
◼ Existential quantifier $ (‘there exists’)
◼ Universal quantifier " (‘for all’)

 Tuple variables qualified by " or $ are called bound variables,


otherwise called free variables.

57
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Existential quantifier used in formulae that must be true for at least
one instance, such as:
Staff(S)  ($B)(Branch(B) 
(B.branchNo = S.branchNo)  B.city = ‘London’)

 Means ‘There exists a Branch tuple with same branchNo as the


branchNo of the current Staff tuple, S, and is located in London’.

58
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Universal quantifier is used in statements about every instance, such as:
("B) (B.city  ‘Paris’)

 Means ‘For all Branch tuples, the address is not in Paris’.

 Can also use ~($B) (B.city = ‘Paris’) which means ‘There are no branches
with an address in Paris’.

59
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Formulae should be unambiguous and make sense.
 A (well-formed) formula is made out of atoms:
 R(Si), where Si is a tuple variable and R is a relation
 Si.a1  Sj.a2
 Si.a1  c
 Can recursively build up formulae from atoms:
 An atom is a formula
 If F1 and F2 are formulae, so are their conjunction, F1  F2; disjunction, F1
 F2; and negation, ~F1
 If F is a formula with free variable X, then ($X)(F) and ("X)(F) are also
formulae.
60
© Pearson Education Limited 1995, 2005
Example - Tuple Relational Calculus
 List the names of all managers who earn more than £25,000.
{S.fName, S.lName | Staff(S) 
S.position = ‘Manager’  S.salary > 25000}

 List the staff who manage properties for rent in Glasgow.


{S | Staff(S)  ($P) (PropertyForRent(P)  (P.staffNo = S.staffNo)  P.city =
‘Glasgow’)}

61
© Pearson Education Limited 1995, 2005
Example - Tuple Relational Calculus
 List the names of staff who currently do not manage any
properties.
{S.fName, S.lName | Staff(S)  (~($P) (PropertyForRent(P)(S.staffNo =
P.staffNo)))}
Or
{S.fName, S.lName | Staff(S)  (("P) (~PropertyForRent(P) 
~(S.staffNo = P.staffNo)))}

62
© Pearson Education Limited 1995, 2005
Example - Tuple Relational Calculus
 List the names of clients who have viewed a property for rent
in Glasgow.
{C.fName, C.lName | Client(C)  (($V)($P)
(Viewing(V)  PropertyForRent(P) 
(C.clientNo = V.clientNo) 
(V.propertyNo=P.propertyNo) 
P.city =‘Glasgow’))}

63
© Pearson Education Limited 1995, 2005
Tuple Relational Calculus
 Expressions can generate an infinite set. For example:
{S | ~Staff(S)}

 To avoid this, add restriction that all values in result must be


values in the domain of the expression.

64
© Pearson Education Limited 1995, 2005
Domain Relational Calculus
 Uses variables that take values from domains instead of tuples of
relations.

 If F(d1, d2, . . . , dn) stands for a formula composed of atoms and


d1, d2, . . . , dn represent domain variables, then:
{d1, d2, . . . , dn | F(d1, d2, . . . , dn)}
is a general domain relational calculus expression.

65
© Pearson Education Limited 1995, 2005
Example - Domain Relational Calculus
 Find the names of all managers who earn more than £25,000.
{fN, lN | ($sN, posn, sex, DOB, sal, bN)
(Staff (sN, fN, lN, posn, sex, DOB, sal, bN) 
posn = ‘Manager’  sal > 25000)}

66
© Pearson Education Limited 1995, 2005
Example - Domain Relational Calculus
 List the staff who manage properties for rent in Glasgow.
{sN, fN, lN, posn, sex, DOB, sal, bN |
($sN1,cty)(Staff(sN,fN,lN,posn,sex,DOB,sal,bN) 
PropertyForRent(pN, st, cty, pc, typ, rms,
rnt, oN, sN1, bN1) 
(sN=sN1)  cty=‘Glasgow’)}

67
© Pearson Education Limited 1995, 2005
Example - Domain Relational Calculus
 List the names of staff who currently do not manage any
properties for rent.
{fN, lN | ($sN)
(Staff(sN,fN,lN,posn,sex,DOB,sal,bN) 
(~($sN1) (PropertyForRent(pN, st, cty, pc, typ,
rms, rnt, oN, sN1, bN1)  (sN=sN1))))}

68
© Pearson Education Limited 1995, 2005
Example - Domain Relational Calculus
 List the names of clients who have viewed a property for rent in
Glasgow.
{fN, lN | ($cN, cN1, pN, pN1, cty)
(Client(cN, fN, lN,tel, pT, mR) 
Viewing(cN1, pN1, dt, cmt) 
PropertyForRent(pN, st, cty, pc, typ,
rms, rnt,oN, sN, bN) 
(cN = cN1)  (pN = pN1)  cty = ‘Glasgow’)}

69
© Pearson Education Limited 1995, 2005
Domain Relational Calculus
 When restricted to safe expressions, domain relational calculus is
equivalent to tuple relational calculus restricted to safe expressions, which
is equivalent to relational algebra.

 Means every relational algebra expression has an equivalent relational


calculus expression, and vice versa.

70
© Pearson Education Limited 1995, 2005
Other Languages
 Transform-oriented languages are non-procedural languages that
use relations to transform input data into required outputs (e.g.
SQL).

 Graphical languages provide user with picture of the structure of the


relation. User fills in example of what is wanted and system returns
required data in that format (e.g. QBE).

71
© Pearson Education Limited 1995, 2005
Other Languages
 4GLs can create complete customized application using limited
set of commands in a user-friendly, often menu-driven
environment.

 Some systems accept a form of natural language, sometimes


called a 5GL, although this development is still at an early stage.

72
© Pearson Education Limited 1995, 2005

También podría gustarte