Soluções da ficha 1 / Solutions for “ficha 1”
No contexto das Bases de Dados, o termo Entidade significa um objecto caracterizável por um conjunto de atributos. Por seu turno, o termo Atributo pode ser visto de forma simples como um objecto, grande
parte das vezes não caracterizável por outros atributos ou por outras partes que o descrevam. Por exemplo, a entidade sócio (o sócio de um vídeo-‐clube), é caracterizável pelos seguintes atributos: num_sócio, que significa o número que é atribuído ao sócio pelo vídeo-‐clube; BI_sócio, cujo significado
é, obviamente, o número do BI do sócio; nome_sócio, que significa o nome que figura no BI do sócio; data_nsc_sócio, que é a data de nascimento do sócio; morada_sócio, tlf_sócio e sexo_sócio são mais três atributos cujo significado não levanta dúvidas.
In the context of Databases, the term Entity means an object that is characterized by a set of attributes. The term Attribute can be viewed simply as an object often not characterized by other attributes. For example, the partner (sócio) entity (the member of a video club), is characterized by the following attributes: num_ sócio, which means the number that is assigned to the member by the video club; BI_ sócio, whose meaning is, of course, the BI number of the partner; nome_ sócio, which means the name that is in the partner's BI; Date_nsc_socio, which is the date of birth of the member; morada_sócio, tlf_sócio and sexo_sócio are three more attributes whose meaning does not raise doubts.
Sendo o sócio uma pessoa, poderíamos à partida pensar em incluir muitos outros atributos: num_contribuinte, local_nascimento, etc.. No entanto, não é previsível qualquer interesse nesses atributos para as aplicações possíveis no contexto de um vídeo-‐clube. A entidade sócio é pois
caracterizada por estes atributos que, por seu turno, não se caracterizam por mais atributos, sendo estes completamente descritos pelo seu significado. No entanto, o significado de cada atributo deverá ser preciso, isto é, não pode ser vago. Desta maneira garante-‐se que o significado das entidades
também será bem definido.
Since a partner (sócio) is a person, we could at first consider to include many other attributes: num_contribuinte, local_nascimento (place of birth), etc. However any interest in these attributes is not
predictable for the possible applications in the context of a video club. The sócio entity is therefore characterized by these attributes which, in turn, are not characterized by more attributes, being completely described by their meaning. However, the meaning of each attribute must be precise, that is,
it can not be vague. This way it is guaranteed that the meaning of the entities will also be well defined.
Um conjunto de entidades encontra-‐se, grande parte das vezes, num esquema de tabela, que é uma estrutura implementável através das ferramenteas que fazem parte dum Sistema de Gestão de Bases de
Dados (SGBD). Segundo a representação E-‐R (Entidade-‐Relação), o conjunto de entidades sócio pode representar-‐se assim:
A set of entities is often found in a schema/table, which is a structure that can be implemented through
the tools that are part of a Database Management System (DBMS). According to the representation E-‐R (Entity-‐Relation), the set of sócio entities can be represented as:
Figura 1
Na notação E-‐R, os rectângulos representam conjuntos de entidades; os losangos representam conjuntos de relações; as linhas ligam atributos aos conjuntos de entidades e conjuntos de relações; as elipses representam atributos; atributos sublinhados representam atributos constituintes da chave
primária.
In E-‐R notation, rectangles represent sets of entities; diamonds represent sets of relations; lines link attributes to the sets of entities and sets of relations; ellipses represent attributes; underlined attributes
represent constituent attributes of the primary key.
DER soluçao para o problema 1 / DER solution for problem 1
Suponhamos que pretendemos criar uma modelo de dados e posteriormente a correspondente BD sobre um video-‐clube. Além do sócio, de que já falámos, existem filmes para alugar aos sócios. Os filmes
caracterizam-‐se pelo nome que os identifica, o ano de lançamento, o preço por dia de aluguer, o número de dias de aluguer «sem multa» e a multa por dia para além da data previsível de entrega. No filme participa pelo menos um actor, bem como pelo menos um realizador. Admitamos que um filme
pertence sempre a um só género (cómico, dramático, etc.) e pertence sempre a uma só editora que é identificada pelo seu nome. Os fimes podem ter uma ou mais cópias. As cópias pertencentes a um filme têm números de cópia seguidos a começar em 1. Por outras palavras, num filme do qual haja 3 cópias,
estas terão como números de cópia, 1, 2 e 3. Alugam-‐se cópias dos filmes aos sócios. Um aluguer é feito sempre numa data e também é caracterizado por uma data previsível de devolução da cópia. No acto de devolução é registado o estado de conservação da cópia; neste acto poderá haver lugar a multa por
entrega tardia.
Suppose we want to create a data model and then the corresponding DB on a video club. Besides the sócio, of which we have already spoken, there are movies (filme) to rent to the members (sócios). Each filme is characterized by the name that identifies it, the year of launch, the price per day of rental, the number of days of rental without a fine and the fine amount per day beyond the expected date of
sócio
tlf_sócio
num_sócio
morada_sócio BI-‐sócio
nome_sócio
data_nsc_sócio
sexo_sócio
delivery. At least one actor is involved in the film, as well as at least one director. Let us assume that a filme always belongs to one genre (comic, dramatic, etc.) and always belongs to a single editora (publisher) which is identified by its name. Movies (filmes) may have one or more copies. Copies belonging to a movie have copy numbers starting at 1, then 2,3,... In other words, in a movie of which there are 3 copies, these will have as copy numbers, 1, 2 and 3. Copies of the films are rented to the members (sócios). A rental is always made on a date and is also characterized by a predictable date of return of the cópia (copy). The state of preservation of the copy is recorded in the return act; In this act there may be a fine for late delivery.
Figura 2
O atributo nome_filme identifica univocamente o filme, ou seja, é uma chave candidata no conjunto de entidades/esquema, já que podemos admitir que não existem dois filmes com o mesmo nome. Porém,
nome_filme é um atributo que pode ocupar 30 ou 40 caracteres, não sendo por isso aconselhável para ser chave designada. Nestes casos é costume criar-‐se um código (cod_filme), numérico e bem mais curto que, identificando também univocamente cada entidade, é escolhido para chave designada. A mesma
técnica é aplicada nos conjuntos de entidades editora e género; isto é, foram criados os atributos cod_editora e cod_género.
The nome_filme attribute uniquely identifies the filme (movie), that is, it is a candidate key in the entity set / schema, since we can admit that there are not two movies with the same name. However,
filme
ano_filme nome_filme cod_filme
preço_dia _filme
género
editora
cod_editora
nome_editora
cod_género
filme_genero
filme_editora
multa_dia _filme
nome_género
dias_sem_multa_filme_filme
nome_filme is an attribute that can occupy 30 or 40 characters, so it is not advisable to be a designated key. In these cases it is customary to create a code (cod_filme), numerical and much shorter that, also
identifying univocally each entity, is chosen for designated key. The same technique is applied in the sets of publisher (editora) and genre (género) entities, that is, the attributes cod_editora and cod_género have been created.
Há uma relação/associação de muitos-‐para-‐um no sentido de filme para género; o losango representa a relação; a seta indica o sentido da associação muitos-‐para-‐um. Por outro lado, a participação de filme em filme_género é total, isto é, cada entidade particular em filme (cada filme concreto) pertence
sempre a um género concreto; o traço duplo representa essa participação de totalidade. Pelo diagrama, vê-‐se que, analogamente, há outra relação/associação de muitos-‐para-‐um no sentido de filme para editora.
There is a many-‐to-‐one relationship from filme to género; the diamond represents the relation; the arrow indicates the direction of the many-‐to-‐one association. On the other hand, the participation of filme in filme_género is total, that is, each particular entity in filme (each concrete filme) always belongs
to a particular género; the double line represents this participation of totality. From the diagram, we see that, analogously, there is another many-‐to-‐one relationship from film to editora.
filme
nome_filme
preço_dia _filme
género
editora
cod_editora
nome_editora
cod_género
filme_genero
filme_editora
multa_dia _filme
nome_género
actor filme_actor
nome_actor
ano_filme cod_filme cod_actor
actor_realizador
realizador
cod_realizador
nome_realizador
cópia
copia_filme
num_cópia
dias_sem_multa_filme_filme
Figura 3
No diagrama, as partes a sombreado não fazem parte da notação DER, servem apenas para pôr em relevo o que abacou ser ser acrescentado ao DER anterior.
In the diagram, the shaded parts are not part of the DER notation, they only highlight what has been
added to the previous DER.
Assim, há uma relação/associação entre filme e actor. A ausência de seta em ambos os sentidos indica que a associação é de muitos-‐para-‐muitos. No entanto, a participação de filme em filme_actor é total,
isto é, cada filme tem que ter sempre pelo menos um actor. A relação filme_actor terá como chave candidata (e designada/primária) a combinação do atributo que é chave designada em filme e o atributo que é chave designada em actor, isto é, (cod_filme,cod_actor). A ordem pela qual são dispostos os
atributos constituintes da chave pode ser à partida qualquer uma; uma análise que, embora não caiba nesta disciplina, poderia levar-‐nos a optar eventualmente por uma disposição que favorecesse as pesquisas mais procuradas.
Análoga à relação/associação filme_actor, existe outra entre filme e realizador; as considerações a ter em conta neste caso, são idênticas. Ver diagrama da figura 3.
Thus, there is a relation / association between filme and actor. The absence of an arrow in both
directions indicates that the association is many-‐to-‐many. However, the participation of filme in filme_ator is total, that is, each filme must always have at least one actor. The relation filme_actor will have as a candidate key (and designated/primary key) the combination of the attribute that is
designated key in film and the attribute that is designated key in actor, that is, (cod_filme, cod_actor). The order in which the attributes constituting the key are arranged may be, say, any one; an analysis that, although it does not fit in this subject, could lead us to opt for an attribute order favoring the most
common searches. Analogous to the relationship / association filme_actor, there is another one between filme and realizador (director); The considerations to be taken into account in this case are identical. See diagram
of figure 3.
Segundo as chamadas especificações funcionais que derivam do enunciado do problema, os números de cópia serão atribuídos a partir de 1 para cada filme; isto quer dizer que no conjunto de entidades cópia
poderão existir várias entidades com o mesmo valor para o atributo num_cópia, o que impossibilita este atributo de, sozinho, ser chave designada. Nestes casos, quando no conjunto de entidades, o conjunto de atributos que surgem, digamos, «naturalmente», não é suficiente para formar chave, o conjunto de
entidades é considerado fraco, sendo que, neste caso, o duplo traço que delimita o rectângulo cópia caracteriza isso mesmo. Nestes casos, para obter uma chave designada, é necessário juntar ao chamado atributo discriminante -‐-‐-‐neste caso o num_cópia -‐-‐-‐ outros atributos que façam parte de outros
conjuntos de entidades ligados a este conjunto. Assim, como toda a cópia pertence a um e um só filme -‐-‐-‐ ver duplo traço de cópia para cópia_filme e seta de cópia_filme para filme -‐-‐-‐ então a chave candidata
(e designada) de cópia inclui o atributo que é chave em filme, ou seja, cod_filme, para além do atributo discriminante, num_cópia, como já foi dito; esta inclusão está representada pelo «duplo losango» de
cópia_filme na mesma figura 3.
According to the so-‐called functional specifications that derive from the problem statement, the copy numbers will be assigned from 1 for each film; this means that in the set of cópia entities there may be several entities with the same value for the num_ cópia attribute, which makes it impossible for this attribute alone to be designated/primary key. In these cases, when in the set of entities the set of attributes that arise, say, "naturally", is not enough to form a key, the set of entities is considered weak; in this case, the double dash delimiting the rectangle cópia denotes that. In these cases, to obtain a designated key, it is necessary to add other attributes that are part of other sets of entities connected to this set, to the so-‐called discriminant attribute -‐-‐-‐ in this case it is num_ cópia -‐-‐-‐. So, since every cópia belongs to one and only one filme -‐-‐-‐ see double line from cópia to cópia_filme and an arrow from cópia_filme to filme -‐-‐-‐ then the candidate (and designated/primary) key of cópia includes the attribute that is key in filme, ie, cod_filme, in addition to the discriminant attribute, num_cópia, as has already been said; this inclusion is represented by the "double diamond" of cópia_film in the same figure 3.
sócio
tlf_sócio
num_sócio
morada_sócio BI_sócio
nome_sócio
data_nsc_sócio
sexo_sócio
filme
nome_filme
preço_dia _filme
género
editora
cod_editora
nome_editora
cod_género
filme_genero
filme_editora
multa_dia _filme
nome_género
actor filme_actor
nome_actor
ano_filme cod_filme cod_actor
filme_realizador
realizador
cod_realizador
nome_realizador
cópia
cópia_filme
num_cópia
aluguer
Aluguer_cópia
data_aluguer
devolução
estado_devolução
data_devolução
aluguer_sócio
dias_sem_multa_filme
Is-‐A
aluguer_sócio
data_prev_dev_aluguer
Figura 4
Segundo o enunciado, relativamente ao conjunto de entidades aluguer surge naturalmente a data_aluguer, atributo que, sozinho não é suficiente para constituir a chave, já que poderão existir
vários alugueres feitos na mesma data. Assim, também este conjunto pode ser considerado como fraco -‐-‐-‐ atenção que o adjectivo fraco apenas se deve à notação DER; não quer dizer que se esteja perante um conjunto de entidades de menor importância como por sugestão podemos ser levados a pensar. Assim,
facilmente se compreende que necessitamos dos atributos que, combinados, identifiquem univocamente qualquer entidade em aluguer (qualquer aluguer). Em consequência disso, as relações aluguer_cópia e aluguer_sócio estão representadas com um duplo losango e a chave candidata de
aluguer será constituída portanto pela combinação de 4 atributos: (cod_filme, num_cópia, num_sócio, data_aluguer); também aqui, a ordem dos atributos não é importante nesta fase. Repare-‐se que não podemos prescindir do atributo num_sócio para a constituição da chave de aluguer porque se o
fizéssemos, estaríamos a impedir que a mesma cópia dum filme fosse alugada duas vezes num mesmo dia. Este conjunto de entidades tem ainda um atributo que corresponde à data prevista de devolução do aluguer (data_prev:_dev_aluguer). This set of entities also has an attribute that corresponds to the
expected date of delivery (data_prev_dev_aluguer).
Naturalmente que, todo o aluguer é feito a um sócio, daí a relação de muitos-‐para-‐um de aluguer para sócio. Ver figura 4.
According to the statement, regarding the set of aluguer (rental) entities, the data_aluguer (rental date) is an attribute that, alone, is not enough to constitute the key, since there will be several leases made on the same date. Thus, this set must also be considered as weak -‐-‐-‐ note that the weak adjective is only due to the DER notation; it does not mean that we are faced with a group of less important entities as by suggestion we can be led to think. Thus, it is easy to understand that we need attributes that, in combination, uniquely identify any entity in aluguer (any rental). As a result, the aluguer_cópia and aluguer_sócio relationships are represented by a double diamond and the candidate key of aluguer will therefore consist of the combination of 4 attributes: (cod_filme, num_cópia, num_sócio, data_aluguer); Here, the order of the attributes is not important too, at this stage. Note that we can not dispense with the num_sócio attribute for the key constitution of aluguer because if we did, we would be preventing the same cópia of a filme from being leased twice on the same day. Of course, any lease is made to a sócio (partner), hence the many-‐to-‐one relationship from aluguer to sócio. See Figure 4. Continuando com o nosso modelo de dados e, atendendo ao evento da devolução do aluguer, aquilo que é, de uma forma simples a entrega da cópia física numa dada data. Poder-‐se-‐ia pensar em
acrescentar um atributo, data_devolução, ao conjunto de atributos de aluguer. Porém, embora esta seja uma solução intuitiva, não é a solução mais robusta. Na verdade, se optássemos por ela, o atributo data_devolução ficaria a maior parte do tempo vazio, o que se procura evitar. Além do mais, o evento
devolução tem, potencialmente, outros atributos naturais, entre eles o estado de conservação da cópia na altura em que esta foi devolvida; isso implicaria ter mais um atributo estado_devolução em aluguer,
que também ficaria vazio (não preenchido) a maior parte do tempo; tal como o atributo data_devolução, também o estado_devolução seria preenchido apenas quando a cópia fosse devolvida -‐
-‐-‐voltaremos a este assunto mais à frente-‐-‐-‐. Posto isto, a solução que pode ser considerada mais robusta e nesse sentido aconselhável, é considerar que devolução é um conjunto de entidades.
Acontece que, entre aluguer e devolução a cardinalidade é de um-‐para-‐um, com a particularidade de a
uma devolução corresponder sempre um aluguer. No entanto, nem a todo o aluguer corresponde uma devolução já que a devolução só ocorre passados dias depois do aluguer ou nunca. Nestes casos de um-‐para-‐um o conjunto de entidades com a participação total herda como sua chave designada, a chave
designada do outro conjunto de entidades. Esta circunstância configura uma estrutura conhecida por Is-‐A (é um); mais concretamente, uma devolução é uma especialização de aluguer. Ver figura 4.
Now, given the event of the return of the aluguer (rental), that is, in a simple way the delivery of the physical copy on a given date. One might think of adding an attribute, data_devoluçao (delivery date), to the set of attributes of aluguer. But while this is an intuitive solution, it is not the most robust solution. In
fact, if we opted for it, the data_devoluçao attribute would be empty (most of the time), which we want to avoid. What's more, the return/delivery event has potentially other natural attributes, including the state of preservation of the cópia at the time it was returned; this would imply having one more
attribute, estado_devoluçao (preservation grade), on aluguer, which would also be empty (unfilled) most of the time; like the data_devoluçao attribute, the estado_devolução attribute would also be filled only when the cópia was delivered -‐-‐-‐ we will return to this subject later -‐-‐-‐. Therefore, the solution that can
be considered more robust, and in that sense advisable, is to consider that devolução (devolution) is a set of entities.
It turns out that the cardinality is one-‐to-‐one between aluguer and devolução, with the particularity of each devolução always corresponds to an aluguer (rental). However, it is not true that every aluguer corresponds to a devolução, since a devolução (a return/devivery) only takes place some days after the
aluguer (rental) act, or never. In these one-‐to-‐one cases the set of entities with the full participation inherits the designated key of the other set of entities to be its designated key. This circumstance configures a structure known as Is-‐A (is one); more specifically, a devolução is an aluguer (rental)
specialization. See Figure 4.
Passagem do modelo de dados em DER para esquemas de tabelas / from data model in DER to
schemas of tables.
A passagem para o esquema de tabelas a partir do DER faz-‐se com regras simples. Grossomodo, a cada conjunto de entidades correponde uma esquema de tabela. Comecemos então por definir os esquemas
de tabelas que não estão em dependência de muitos-‐para-‐um a partir delas; por exemplo os esquemas sócio, género, editora, actor e realizador.
The “translation” from DER to table schemas is done with simple rules. Basically each set of entities
corresponds to a table schema. Let's start by defining the table schemas that are not in many-‐to-‐one dependency from them; for example the schemas sócio, género, editora, actor and realizador.
Sócio=(num_sócio, nome_sócio, bi_sócio,data_nsc_sócio, morada_sócio, tlf_sócio, sexo_sócio)
Género=(cod_género, nome_genero) Editora=(cod_editora, nome_editora) Actor=(cod_actor, nome_actor)
Realizador=(cod_realizador, nome_realizador)
Nestes casos, basta incluir como campos/atributos do esquema de tabela os mesmos atributos que no DER caracterizam as entidades, ignorando as ligações a outras relações. Os atributos a sublinhado são as
chaves designadas. Entre as chaves candidatas num_sócio e bi_sócio, foi escolhida a primeira como chave designada (primária) por ser mais curta.
In these cases, the same attributes that in the DER characterize the entities, ignoring the links to other relationships, are simply included as fields / attributes of the table schema. The underlined attributes are the designated keys. Among the candidate keys num_sócio and bi_sócio , the former was chosen as designated key (primary) because it was shorter. Vejamos agora o caso do esquema filme, tendo em conta que, para os casos dos conjuntos de entidades
em dependência muitos-‐para-‐um há duas opções: o “modelo simplificado” e o “modelo não simplificado”. No modelo não simplificado, o esquema terá como atributos apenas aqueles que caracterizam as entidads no DER, tal como nos casos anteriores. Assim, no caso do esquema filme
teremos:
Now let us see the case of the filme schema, taking into account that for the cases of entity sets in many-‐to-‐one dependency there are two options: the "simplified model" and the "non-‐simplified model". In the
non-‐simplified model, the schema will have as attributes only those that characterize the entities in the DER, as in the previous cases. Thus, in the case of the filme schema we will have:
Filme=(cod_filme, nome_filme, ano_filme, preço_dia_filme, dias_sem_multa_filme, multa_dia_filme)
No entanto, tendo em conta que o conjunto de entidades filme está relacionado com o conjunto editora através da relação filme_editora, é necessário representar também esta relação. Para tal, e tendo em conta que a dependência entre filme e filme_editora é de cardinalidade um-‐para-‐um (repare-‐se que a
um filme corresponde apenas um filme_editora e vice-‐versa), então o esquema filme_editora terá como atributos aqueles que são chave nos conjuntos de entidades filme e editora, ou seja cod_filme e cod_editora; contudo, a chave deste esquema será apenas cod_filme, já que cada entidade isolada de
filme_editora tem um valor diferente para cod_filme; repare-‐se que a chave não poderia ser cod_editora porque duas entidades neste conjunto podem ter o mesmo valor para cod_editora. Assim, eis o esquema filme_editora segundo o modelo “não simplificado”:
However, taking into account that the set of filme entities is related to the editora set through the filme_editora relationship, it is also necessary to represent this relationship. For this, and taking into account that the dependency between filme and filme_editora is a one-‐to-‐one cardinality (note that a
filme_editora corresponds to only one filme, and vice versa), then the filme_editora schema will have
attibutes corresponding to those which are keys in the filme and editora entity sets, ie cod_filme and cod_editora; however, the key to this schema will be cod_filme, since each isolated entity of
filme_editora has a different value for cod_filme; note that the key could not be cod_editora because two entities in this set can have the same value for cod_editora. Thus, here is the filme_editora schema according to the "non-‐simplified" model:
Filme_editora=(cod_filme, cod_editora)
No entanto, segundo o “modelo simplificado”, dado que quer a chave do esquema filme quer a do
esquema filme_editora é cod_filme e a cardinalidade é de um-‐para-‐um e total em ambos os sentidos, então faz sentido não incluir o esquema filme_editora no conjunto final de tabelas e incluir cod_editora desse esquema no esquema filme. Na verdade, cada filme concreto pertence a exactamente uma
editora concreta e por isso, o atributo que é a chave designada da editora ( o «apontador» para a editora) pode e deve figurar nos atributos do esquema filme. Um raciocínio análogo aplica-‐se relativamente à chave designada do esquema género que também é «importado» como atributo para o
esquema filme, já que, entre filme e género existe também uma relação de muitos-‐para-‐um. Assim, o esquema filme segundo o “modelo simplificado” tem a seguinte constituição:
However, according to the "simplified model", since both the keys of the filme and filme_editora is cod_filme and the cardinality is one-‐to-‐one and total in both directions, then it makes sense not to include filme_editora schema in the final set of tabes, and include cod_editora of that schema in the filme schema. In fact, each individual filme belongs to exactly one particular editora, so the attribute that is the designated key of the editora (say, the "pointer" for the publisher) can and should be listed in the filme schema attributes. An analogous reasoning applies to the designated key of the género schema which is also 'imported' as an attribute for the filme schema, since between filme and género there is also a many-‐to-‐one relationship. Thus, according to the "simplified model", the filme schema has the following constitution:
Filme=(cod_filme, nome_filme, ano_filme, preço_dia_filme, dias_sem_multa_filme, multa_dia_filme,
cod_género, cod_editora)
Em vez do anterior esquema que não inclui os atributos cod_editora e cod_filme.
Instead of the previous schema that does not include cod_editora and cod_filme attibutes.
Em suma, os “modelo não simplificado” e “modelo simplificado” diferem no que se segue. Se entre os conjuntos A e B existe uma relação de muitos-‐para-‐um (chamemos-‐lhe A_B), então no “modelo não simplificado” teremos 3 esquemas: o esquema A com os atributos que o caracterizam no DER sendo um
deles a sua chave (Ka); o esquema B também com os atributos que o caracterizam no DER, sendo um deles a sua chave (Kb); e um terceiro esquema A_B com os artributos Ka e Kb, sendo Ka a chave deste esquema. No “modelo simplificado” o esquema A_B não é incluído no conjunto final de tables, o
esquema B mantém não se altera mas o esquema A inclui como atributo aquele que é chave no esquema B, ou seja Kb.
In short, the "non-‐simplified model" and "simplified model" differ in what follows. If there is a many-‐to-‐one relationship between sets A and B (let's call it A_B), then in the "non-‐simplified model" we will have 3
schemas: schema A with the attributes that characterize it in DER being one of them its key (Ka); schema B also with the attributes that characterize it in the DER, one of them being its key (Kb); and a third schema A_B with the Ka and Kb attributes, Ka being the key to this schema. In the "simplified model",
schema A_B does not exist in the final set of tables, schema B maintains no change but schema A includes the attribute which is key in schema B,that is Kb, as its attribute.
Continuando a nossa análise, e daqui em diante segundo o “modelo simplificado”, existe uma relação de
cardinalidade diferente (muitos_para_muitos) de actor para filme. Este tipo de relação origina sempre uma esquema adicional que recebe muitas vezes o mesmo nome da relação, ou um que melhor capte o seu significado; neste caso filme_actor. Os atributos deste esquema são os atributos que constituem as
chaves de cada conjunto de entidades que está na origem desta relação de muitos-‐para-‐muitos e, a reunião/combinação de todos estes atributos contitui a chave deste novo esquema. Ou seja:
Continuing our analysis, and hereafter according to the "simplified model," there is a different cardinality
relationship (many_to_many) from actor to film. This type of relationship always gives rise to an additional schema that often receives the same name from the relationship, or another one that better captures its meaning; in this case, filme_actor. The attributes of this schema are the attributes that
constitute the keys of each set of entities that are at the origin of this many-‐to-‐many relationship, and the combination of all these attributes completes the key of this new schema. That is:
Filme_actor=(cod_filme,cod_actor)
Relativamente à relação filme_realizador aplica-‐se o mesmo raciocínio; daí o esquema:
The same reasoning applies to the filme_realizador relationship; hence the schema:
Filme_realizador=(cod_filme,cod_realizador)
De notar que, poderíamos admitir um atributo que retratasse em texto livre o papel do actor concreto no filme concreto (papel_filme_actor). Esse atributo seria acrescentado ao esquema filme_actor mas
não faria parte da chave.
Notice that we could admit an attribute that would portray in free text the role of the concrete actor in the concrete film (papel_filme_actor, meaning role_of_actor_in_movie). This attribute would be
appended to the filme_actor schema but would not be part of the key.
Relativamente ao esquema cópia, existem apenas os atributos num_cópia, que é o chamado atributo discriminante como já foi referido, e cod_filme (a chave designada no esquema filme; ver a seta e o seu
sentido na relação cópia_filme). Este último atributo irá completar a chave designada neste esquema. Na verdade, uma cópia concreta pertence sempre a um dado filme:
For the cópia schema, there are only the num_copy attribute, which is called the discriminant attribute
as already mentioned, and cod_filme (the designated key in the filme schema; see the arrow and its direction in the relationship cópia_filme). This last attribute will complete the designated key in this schema. In fact, a concrete cópia always belongs to a filme:
Cópia=(cod_filme,num_cópia)
Relativamente ao esquema aluguer, tendo em conta que deriva dum conjunto de entidades fracas, este terá como chave o atributo discriminante data_aluguer e os atributos que constituem a chave designada
do esquema cópia e do esquema sócio; ver figura 4.
Regarding the aluguer schema, given that it derives from a set of weak entities, this key will have the discriminant attribute data_aluguer and the attributes that constitute the designated key of the cópia
and sócio schemas.; see figure 4.
Aluguer=(cod_filme,num_cópia,data_aluguer,num_sócio, data_prev_dev_aluguer)
Por fim, o esquema devolução, que decorre do conjunto de entidades com o mesmo nome, terá como
chave a mesma chave do esquema aluguer, já que existe uma relação de um_para_um entre os dois conjuntos de entidades mas com participação total por parte da devolução. Este esquema terá ainda como atributos, data_devolução e estado_devolução; estes já não integrantes da chave do esquema.
Finally, the devolução (copy delivery) schema, which is derived from the set of entities with the same name, will be keyed to the same key as the aluguer schema, since there is a one_to_one relationship between the two sets of entities but with a full participation by the devolução. This schema will also have attributes, data_devolução and estado_evolução (physical state of the copy); these attributes are not part of the schema key.
Devolução=(cod_filme, num_cópia, data_aluguer, num_sócio, data_devolução, estado_devolução)
Em resumo, são os seguintes os esquemas correspondentes ao “clube de vídeo”:
In summary, the following are the schemas corresponding to the "video club":
Sócio=(num_sócio, nome_sócio, bi_sócio,data_nsc_sócio, morada_sócio, tlf_sócio, sexo_sócio) Género=(cod_género, nome_genero) Editora=(cod_editora, nome_editora)
Actor=(cod_actor, nome_actor) Realizador=(cod_realizador, nome_realizador) Filme=(cod_filme, nome_filme, ano_filme, preço_dia_filme, dias_sem_multa_filme, multa_dia_filme,
cod_género, cod_editora) Filme_actor=(cod_filme,cod_actor) Filme_realizador=(cod_filme,cod_realizador)
Cópia=(cod_filme,num_cópia) Aluguer=(cod_filme,num_cópia,data_aluguer, num_sócio, data_prev_dev_aluguer) Devolução=(cod_filme, num_cópia, data_aluguer, num_sócio, data_devolução, estado_devolução)
Exercício 2 / Exercício 2:
Crie um Modelo de Dados para consultório médico. Considere consultas, doentes, médicos e
especialidades (estomatologia, pneumologia, etc.). Cada médico tem uma especialidade. Nas consultas os médicos receitam medicamentos (um ou mais). Existem também marcações de consultas. No início de cada dia, cada médico atribui às suas consultas um número de ordem sequencial que começa em 1 e
continua 2, 3...
Use the DER approach to create a data model for a medical clinic. Present the set of schemas and their keys resulting from that model. Consider appointments, patients, doctors and specialities (Stomatology,
Pneumology, etc.). Each doctor has a speciality. In the appointments, doctors may prescribe medicines (one or more). There are bookings for appointments. Each new day, the appointments for each doctor have a sequential number, starting by 1, then 2, 3…
Solução do exercício 2:
Cod_medico
Especialidade Médico
Consulta Medicamento
Doente
Nome_especialidade
Cod_especialidade
Nome_medico
Nome_doente
Data_marc_consulta cod_medicamento
Nome_medicamento
Cod_doente
Qt_receita
Med_esp
receita
data_consulta
Feita_a
Consulta
con_med
N_ord_consulta
Especialidade=(cod_especialidade, nome_especialidade) Doente=(cod_doente, nome_doente)
Medicamento=(cod_medicamento, nome_medicamento) Médico=(cod_médico, nome_médico, cod_especialidade) Consulta=(data_consulta, n_ord_consulta, cod_médico, data_marc_consulta,cod_doente)
Receita=(data_consulta, n_ord_consulta, cod_médico, cod_medicamento, Qt_receita)
Para este problema, se admitíssemos que num mesmo dia, um doente não tinha mais do que uma
consulta, o DER do modelo de dados correspondente seria.
For this problem, if we were to admit that on the same day, a patient had only one appointment, the DER of the corresponding data model would be.
Solução (b) do exercício 2 / solution(b) for exercise 2:
Cod_medico
Especialidade Médico
Consulta Medicamento
Doente
Nome_especialidade
Cod_especialidade
Nome_medico
Nome_doente
Data_marc_consulta cod_medicamento
Nome_medicamento
Cod_doente
Qt_receita
Med_esp
receita
data_consulta
Consulta
Feita_ao
con_med
N_ord_consulta
Especialidade=(cod_especialidade, nome_especialidade) Doente=(cod_doente, nome_doente)
Medicamento=(cod_medicamento, nome_medicamento) Médico=(cod_médico, nome_médico, cod_especialidade) Consulta=(data_consulta, cod_doente, n_ord_consulta, cod_médico, data_marc_consulta)
Receita=(data_consulta, cod_doente, cod_medicamento, Qt_receita)
3) Use the DER approach to create a data model for a store. Present the set of tables and their keys resulting from that model.
The store sells (venda) products to customers (clientes). Customers have code and name. The store
orders suppliers (fornecedores). Each product, with name and code, has a type and a selling price (preço). Each product type has code and name also. The suppliers have name, address (morada) and, for each product a price and a delivery time (prazo de entrega) for the orders (encomendas).
Solução do exercício 3 / solution for exercise 3:
Produto
Fornecedor
TipoProd
Encomenda
Cliente
venda
Prod_forn
Nome_produto cod_produto Preço_prod_forn Nome_fornecedor cod_fornrcedor
Prod_tipo
data_encomendaonsulte
Enc_forn
Qt_enc_forn
cod_tipoprod nome_tipoprod
data_venda
cod_encomenda
cod_venda
venda_clientee
Venda_prod
Morada_fornecedor
Preço_venda__produto
cod_cliente
nome_cliente
qt_venda
TipoProd=(cod_tipoprod, nome_tipoprod) Fornecedor=(cod_fornecedor, nome_forecedor,morada_fornecedor)
Cliente=(cod_cliente,nome_cliente) Produto=(cod_produto,nome_produto,preço_venda_produto, cod_tipoprod) Prod_forn=(cod_produto,cod_fornecedor,preço_prod_forn)
Encomenda=(cod_encomenda,data_encomenda) Enc_forn=(cod_encomenda, cod_produto, cod_fornecedor, qt_enc_forn) Venda=(cod_venda, data_venda,cod_produto,qt_venda,cod_cliente)
Top Related