How to describe the specific cardinality constraints in e-r diagram? - database

I'm learning database this semester. The homework on e-r model really confuses me.
The homework is drawing the e-r diagram about a vegetable market: A Vegetable Market has a collection of numbered stalls. Each stall has a name (unique) and sells at least one kind of vegetables (each kind of which has a name). Each stall sells each vegetable at its own particular price. Each farm grows some (at least one, but not all) of the vegetables, but a vegetable must be grown by at least one farm. Each farm has one name (unique) and address. Each stall buys each vegetable from only one farm at a particular price they have agreed.
My question is that how to describe the constraint "(at least one, but not all)" in the requirement?
Another question is that since vegetables don't have primary key or discriminator, should they be treated as entities? Or should they be treated as somethings else like attributes?
Here's my answer:
(source: rrimg.com)

Ad.1
As far as I know it is impossible to place on a ERD diagram information like at least one, but not all, I would simply mark the relationship as one or more, which is possible. The only thing that comes to my mind is placing an appropriate comment, stating that requirement.
Ad. 2
Yes, vegetable in my opinion should be represented as a separated entity. If you wanted to place it as an attribute, you coud do this as an attribute of entity "Farm_grows", but you will not be able to preserve uniqueness, you will have to have some key anywas, and finally the worst thing is that, it wouldn't be 3NF.
My propositions is on the below diagram - unfortunatelly I do not have a tool that supports your notation (I know it would be possible to do it in Visio, but you shouldn't have any problems translating my notation to yours).
The difference in comparison to yours is that I have one relationship for SELL and BUY, which is STALL_VEGETABLE. Why is that so? Because of this requirement:
"Each stall buys each vegetable from only one farm at a particular price they have agreed."
My model preserves that the Stall sells only those vegetables, that it bought, and also it because stall_name and vegetable_name are withing PK, it is impossible for Stall to buy one vegetable from different farms - your model allows that.

Related

how to model many 'many-to-many' relationships in rdbms?

I need to create a data model for an education based application. The question I want to ask is is it better to make one junction table for two tables with many-to-many relation or create one big junction table to deal with all many-to-many relationships?
Say, I have student, tutor, subject, grade tables.
student and tutor are in many-to-many
tutor and subject are in many-to-many
tutor and grade are also in many-to-many
A student can have many tutors for one subject of one grade.
There can be many tutors for one subject of one grade.
A subject of one grade can be taught by many tutors.
Above are just a few examples of the relationships.
My question is how to model these relationships efficiently? Should I have one junction table for each of the relationships or should I combine them into one big bridge table?
So, if I have a class table as well, then from the big bridge table I can get for which class which tutor taught which subject of what grade along with other details of the class.
Let's assume the database is not yet electronic, but a good old filing cabinet instead.
Let's assume the database is for a library, and there are a couple of distinct sorts of "many-to-many info" to be maintained : authors to books (coauthored books have >1 author), readers to books, readers to readers, book availability in possibly multiple site locations of the library, ...
Would you ever think of stashing all those distinct sorts of information in one big filing cabinet ? Imagine what the consequences are for its users ? Sometimes you'll be prohibited to do something "readers to books" merely because someone else is right there doing something "readers to readers". If and when you manage to gain access and it's finally your turn do so something, say "authors to books", your work will be slowed down because all the "readers to books" stuff might come in between and you'll have to spend extra time merely skipping the unneeded stuff. If a "conversion operation" must be performed, say, a new kind of many-to-many stuff is discovered and must be integrated in the single filing cabinet, the entire database is inaccessible while the conversion operation is being performed (people adding filing cards of a color that wasn't yet in use). Etc. etc. . Those undesirable properties carry over almost 1-1 to the electronic equivalent.
As someone else put it : don't be afraid of tables. It's what a DBMS is good at.
EDIT
Brief : just keep it at one table per fact type, and abstain from making (/trying to discover) geeky abstractions like "they're all just properties" / "they're all just some many-to-many-relation" / ... . They're geeky because an end user/business user will not "see" it. And thus there is no business value in making them.

Can or Should an ERD Action involve more than 2 Entities?

This is an problem about drawing ERD in one of my course:
A local startup is contemplating launching Jungle, a new one stop
online eCommerce site.
As they have very little experience designing and implementing
databases, they have asked you to help them design a database for
tracking their operations.
Jungle will sell a range of products, and they will need to track
information such as the name and price for each. In order to sell as
many products as possible, Jungle would like to display short reviews
alongside item listings. To conserve space, Jungle will only keep
track of the three most recent reviews for each product. Of course, if
an item is new (or just unpopular), it may have less than three
reviews stored.
Each time a customer buys something on Jungle, their details will be
stored for future access. Details collected by Jungle include
customer’s names, addresses, and phone numbers. Should a customer buy
multiple items on Jungle, their details can then be reused in future
transactions.
For maximum convenience, Jungle would also like to record credit card
information for its users. Details stored include the account and BSB
numbers. When a customer buys something on Jungle, the credit card
used is then linked to the transaction. Each customer may be linked to
one or more credit cards. However, as some users do not wish to have
their credit card details recorded, a customer may also be linked to
no credit cards. For such transactions, only the customer and product
will be recorded.
And this is the solution:
The problem is the Buys action connect with 3 others entities: Product, Customer, and Card. I find this very hard to read and understand.
Is an action involving more than 2 entities common in production? If it is, how should I understand and use it? Or if it's not, what is the better way of design for this problem?
While the bulk of relationships in practice are binary relationships, ternary and higher relationships are normal elements of the entity-relationship model. Some examples are supplies (supplier_id, product_id, region_id) or enrolled (student_id, course_id, semester_id). However, they often get converted into entity sets via the introduction of a surrogate identifier, due to dislike of composite keys or confusion with network data models in which only directed binary relationships are supported.
Reading cardinality indicators on non-binary relationships are a common source of confusion. See my answer to designing relationship between vehicle,customer and workshop in erd diagram for more info on how I handle this.
Your solution has some problems. First, Buys is indicated as an associative entity, but is used like a ternary relationship with an optional role. Neither is correct in my opinion. See my answer to When to use Associative entities? for an explanation of associative entities in the ER model.
Modeling a purchase transaction as a relationship is usually a mistake, since relationships are identified by the (keys of the) entities they relate. If (CustomerID, ProductID) is identifying, then a customer can buy a product only once, and only one product per transaction. Adding a date/time into the relationship's key is better, but still problematic. Adding a surrogate identifier and turning it into a regular entity set is almost certainly the best course of action.
Second, the Crow's foot cardinality indicators are unclear. It looks like customers and products are optional in the Buys relationship, or even as if multiple customers could be involved in the same transaction. There are three different concepts involved here - optionality, participation and cardinality - which should preferably be indicated in different ways. See my answer to is optionality (mandatory, optional) and participation (total, partial) are same? for more on the topic.
A card is optional for a purchase transaction. From the description, it sounds as if cards may participate totally, meaning we won't store information about a card unless it's used in a transaction. Furthermore, only a single card can be related to each transaction.
A customer is required for a purchase transaction, and it sounds like customers may participate totally, meaning we won't store information about customers unless they purchase something. Only a single customer can be related to each transaction.
Products are required for a purchase transaction, and since we'll offer products before they're bought, products will participate partially in transactions. However, multiple products can be related to each transaction.
I would represent transactions for this problem with something like the following structure:
I'm not saying converting a ternary or higher relationship into an entity set is always the right thing to do, but in this case it is.
Physically, that would require two tables to represent (not counting Customer, Product, Card or ProductReview) since we can denormalize TransactionCustomer and TransactionCard into Transaction, but TransactionProduct is a many-to-many relationship and requires its own table (as do ternary and higher relationships).
Transaction (TransactionID PK, TransactionDateTime, CustomerID, CardID nullable)
TransactionProduct (TransactionID PK, ProductID PK, Quantity, Price)

Entity Relationship Diagram - Where are the purchases?

Considering that this community has questions related to modeling databases, I am here seeking help.
I'm developing an auction system based on another one seen in a book I'm reading, and I'm having trouble. The problem context is the following:
In the auction system, a user makes product announcements (he/she defines a product). It defines
the product name, and the initial offer (called initial bid). The initial bid expresses the minimum amount to be offering. A
product only exists in the database when it is announced by a user. A
user defines a number of products, but a product belongs to a single
user.
Every product has an expiration date. When a certain date arrives, if
there are no offers for the product, it is not sold. If there are
offers for the product, the highest bidder wins the given product.
The offers have a creation date, and the amount offered. An offer is
made to a product from a user. A user can make different offers for
different products. A product can be offered by different users. The
same user can not do more than two offers for the same product.
This kind of context for me is easy to do. The problem is that I need to store a purchase. (I'm sorry, but I do not know if the word is that in English). I need a way to know which offer was successful, and actually "bought" a product. Relative to what was said, part of my Conceptual Model (Entity Relationship Diagram) is as follows:
I've tried to aggregate USERS with PRODUCTS, and make a connection/relationship between the aggregation and PRODUCTS, which would give me the PURCHASES event. When this was broken down (decomposed) I would have a table showing which offer bought what product.
Nevertheless, I would have a cardinality problem. This table would have two foreign keys. One for BIDS, and the other for PRODUCTS. This would allow an N-N relationship of these two, meaning that I could save more than one bid as the buyer of a product, or that the same bid could "buy" many products (so I say in the resulting PURCHASES table).
Am I not seeing something here? Can you guys help me with this? Thank you for reading, for your time, and patience. And if you need some more detail, please do not hesitate to ask.
EDIT
The property "Initial Bid" on the PRODUCTS entity is not a relationship.
This property represents a monetary value, a minimum amount that an offer must have to be given to a particular product.
You are approaching things backwards. First we determine a relevant application relationship, then we determine its properties. Given an application relationship and the possible application situations that can arise, only certain relationship/association sets/tables can arise. A purchase can have only one bid per product and one product per bid. So it is just a fact that the bid:product cardinality of PURCHASES is 1:1. Say so. This is so regardless of what other application relationships you wish to record. If it were a different application relationship between those entities then the cardinality might be different. Wait--USERS_PRODUCTS and BIDS form exactly such a pair of appplication relationships, with user:product being 1:0..N for the former and 0..N:0..N for the latter. Cardinality for each participant reflects (is a property of) the particular application relationship that a diamond represents.
Similarly: Foreign keys are properties of pairs of relationship/association sets/tables. Declaring them tells the DBMS to enforce that participant id values appear in entity sets/tables. Ie {bid} referencing BIDS and {product} referencing PRODUCTS. And candidate keys (of which one can be a primary key) are a property of a relationship set/table. It is the candidate keys of PURCHASES that lead to declaration of a constraint that enforces its cardinality. It isn't many:many on bid:product because "bid BID purchased product PRODUCT at price $AMOUNT on date DATE" isn't many:many on bid:product. Since either its bid or its product uniquely identify a purchase both {bid} and {product} are candidate keys.
Well... I tried to follow the given advices, and also tried to follow what I had previously spoken to do, using aggregation. It seems to me that the result is correct. Please observe:
Of course, a user makes offers for products. A user record can relate to multiple records in PRODUCTS. Likewise, a product can be offered by multiple users, and thus, a record in PRODUCTS can relate to multiple records on USERS. If I'm wrong on this, please correct me.
Looking at purchase, we see that a product is only properly purchased by a single bid. There is no way to say that a user buys a product, or a product purchase itself. It is through the relationship between USERS and PRODUCTS that an bid is created, and it is an bid that is able to buy a product. Thus, it is necessary to aggregate such a relationship, then set the purchase event.
We must remember that only one product can be purchased for a single bid. So here we have a cardinality of 1 to 1. Decomposition here will ask discretion of the data modeler.
By decomposing this Conceptual Model, we will have the following Logic Model:
Notice how relationships are respected with appropriate attributes. We can know who announced a product (the seller), and we can know what offers were made to it.
Now, as I said before, there is the PURCHASES relationship. As we have a relationship of 1 to 1 here, the rule tells us that we must choose which side the relationship will be interpreted (which entity shall keep such a relationship).
It is usually recommended to keep the relationship on the side that is likely in the future to become a "many". There is no need to do so in this case because it is clear that this relationship can not be preserved in a BIDS record. Therefore, we maintain such a relationship portrayed by "Winner Bid" on the PRODUCTS entity. As you can see, I set a unique identifier for BIDS. By defining the Physical Model, we have a surrogate key.
Well, I finish my answer here, but I think I can not consider it right yet. I would like someone to comment anything if possible. Thank you.
EDIT
I'd like to apologize. It seems that there was a mistake on my part. Well, I currently live in Brazil, and here we learn the ER-Diagram in a way that seems to me to be different from what many of you are used to. Until yesterday I've been answering some questions related to the subject here in the community, and I found odd certain different notations used. Only now I'm noticing that we are not speaking the same language. I believe it was embarrassing for me in a way. I'm sorry. Really, I'm sorry.
Oh, and one more thing (it may be interesting for someone):
The cardinality between BIDS and PRODUCTS is really wrong. It should
be 0 to 1 in both, as was said in the comments.
There are no relationships relating with relationships here. We have
what is called here (in my country, or in my past course)
"Aggregation" (Represented in the first drawing by the rectangle with clipped lines). The internal relationship (BIDS) when decomposed will
become an entity, and the relationship between BIDS and PRODUCTS is
made later. An aggregation says that a relationship needs to be resolved first so that it can relate with another entity. This creates a certain restriction, which may be necessary in certain business rules. It says that the joining of two entities define records that relate to records of another entity.
Certain relationships do not necessarily need to be named. Once you
break down certain types of relationships, there is no need (it's
optional) to name them (between relations N to N), especially if new
relationship does not arise from these. Of course, if I were to name the white relationships presented, we then would have USER'S BIDS (between USERS and BIDS), and PRODUCT'S BIDS (between BIDS and PRODUCTS).
With respect to my study material, it's all in portuguese, and I believe you will not understand, I do not know. But here's one of the books I read during my past classes:
ISBN: 978-85-365-0252-6
Title: PROJETO de BANCO de DADOS Uma Visão Prática
Authors: Felipe Machado, Mauricio Abreu
Publishing company: EDITORA ÉRICA
COVER:
LINK:
http://www.editorasaraiva.com.br/produtos/show/isbn:9788536502526/titulo:projeto-de-banco-de-dados-uma-visao-pratica-edicao-revisada-e-atualizada/
Well... What do I do now? Haha... I do not know what to do. I'll leave my question here. If someone with the same method that I can help me, I'll be grateful. Thank you.
To record the winning bid requires a functional dependency Product ID -> Bid ID. This could be implemented as one or more nullable columns (since not all products have been purchased yet) in the Products table, or better in a separate table (Purchases) using Product ID as primary key.

How far does one go to eliminate duplicate data in a database?

How far does one go to eliminate duplicate data in a database? Because you could go OTT and it would get crazy. Let me give you an example...
If I were to create a Zoo database which contains a table 'Animal' which has a 'name', 'species' and 'country_of_birth'
But there will be duplicate data there as many animals could come from same country and there could be lots of tigers, for example.
So really there should be a 'Species' table and a 'Country_of_birth' table
But then after a while you would have tons of tables
So how far do you go?
In this question I am just using one table as an example. One row in the Animal table stores information about a single animal in the zoo. So that animal's name, species and country of birth, as well as a unique animalID.
But there will be duplicate data there as many animals could come from
same country and there could be lots of tigers, for example.
This suggests you want to keep track of individual animals, not just kinds of animals. Let's assume that the zoos use some kind of numeric tattoo or microchip to identify individual animals.
Assume this sample data is representative. (It's not, but it's ok for teaching.)
Animals
Predicate: Animal having microchip <chip_num> of species <species>
has name <name> and was born in <birth_country_code>.
chip_num name species birth_country_code
--
101234 Anita Panthera tigris USA
101235 Bella Panthera tigris USA
101236 Calla Panthera tigris USA
101237 Dingo Canis lupus CAN
101238 Exeter Canis lupus CAN
101239 Bella Canis lupus USA
101240 Bella Canis lupus CAN
There's no redundant data in that table. None of those columns can be dropped without radically changing the meaning of that table. It has a single candidate key: chip_num. It's in 5NF.
Values are repeated in non-key columns. That's kind of the definition of non-key (non-prime) columns. Values in key columns (or sets of key columns) are unique; values in non-key columns aren't.
If you want to restrict the values in "birth_country_code" to the valid three-letter ISO country codes, you can add a table of valid three-letter ISO country codes, and set a foreign key reference to it. This is generally a Good Thing, but it has nothing to do with normalization.
iso_country_code
--
CAN
USA
You could do the same thing again for "species". That, too, would generally be a Good Thing, and it, too, would have nothing to do with normalization.
First you decide What the table is supposed to carry information about. In your example. is the table about individual animals? or is it about species of animals and how many of each species? The fact that you have country of birth might be an indicator that someone wants it to be the former. If that is the case you must have a key that identifies individual animals. You have an attribute, (a property) that is associated with individuals, so each row must (should?) represent an individual. You should read up Here on the database modeling concepts of Identity, and Individuation.
And to do this properly, actually, you do this for each thing in your data model, and then convert that model into database tables.
It comes down to deciding what is important to your system.
Deciding whether something (your e.g. "country of birth") is merely an attribute or is instead a full-blown entity in its own right depends on what else your system needs to know about countries and how many attributes your system may track that are fully functionally dependent on the country.
You should also consider whether your attributes are susceptible to update anomalies. If your statement of country in the animal table is in the form of the full official name of the country, then you might be at risk if, for example, "The Belgian Congo" suddenly becomes "The Democratic Republic of the Congo" - oh wait, that already happened!
The rules of normalization are not sacrosanct. They are pretty darn useful rules of thumb that are intended to keep you out of trouble, most of the time. Still, rules are made to be broken - but you should only break them knowingly and with a carefully considered understanding of the consequences.

a layman's term for identifying relationship

There are couples of questions around asking for difference / explanation on identifying and non-identifying relationship in relationship database.
My question is, can you think of a simpler term for these jargons? I understand that technical terms have to be specific and unambiguous though. But having an 'alternative name' might help students relate more easily to the concept behind.
We actually want to use a more layman term in our own database modeling tool, so that first-time users without much computer science background could learn faster.
cheers!
I often see child table or dependent table used as a lay term. You could use either of those terms for a table with an identifying relationship
Then say a referencing table is a table with a non-identifying relationship.
For example, PhoneNumbers is a child of Users, because a phone number has an identifying relationship with its user (i.e. the primary key of PhoneNumbers includes a foreign key to the primary key of Users).
Whereas the Users table has a state column that is a foreign key to the States table, making it a non-identifying relationship. So you could say Users references States, but is not a child of it per se.
I think belongs to would be a good name for the identifying relationship.
A "weak entity type" does not have its own key, just a "partial key", so each entity instance of this weak entity type has to belong to some other entity instance so it can be identified, and this is an "identifying relationship". For example, a landlord could have a database with apartments and rooms. A room can be called kitchen or bathroom, and while that name is unique within an apartment, there will be many rooms in the database with the name kitchen, so it is just a partial key. To uniquely identify a room in the database, you need to say that it is the kitchen in this particular apartment. In other words, the rooms belong to apartments.
I'm going to recommend the term "weak entity" from ER modeling.
Some modelers conceptualize the subject matter as being made up of entities and relationships among entities. This gives rise to Entity-Relationship Modeling (ER Modeling). An attribute can be tied to an entity or a relationship, and values stored in the database are instances of attributes.
If you do ER modeling, there is a kind of entity called a "weak entity". Part of the identity of a weak entity is the identity of a stronger entity, to which the weak one belongs.
An example might be an order in an order processing system. Orders are made up of line items, and each line item contains a product-id, a unit-price, and a quantity. But line items don't have an identifying number across all orders. Instead, a line item is identified by {item number, order number}. In other words, a line item can't exist unless it's part of exactly one order. Item number 1 is the first item in whatever order it belongs to, but you need both numbers to identify an item.
It's easy to turn an ER model into a relational model. It's also easy for people who are experts in the data but know nothing about databases to get used to an ER model of the data they understand.
There are other modelers who argue vehemently against the need for ER modeling. I'm not one of them.
Nothing, absolutely nothing in the kind of modeling where one encounters things such as "relationships" (ER, I presume) is "technical", "precise" or "unambiguous". Nor can it be.
A) ER modeling is always and by necessity informal, because it can never be sufficient to capture/express the entire definition of a database.
B) There are so many different ER dialects out there that it is just impossible for all of them to use exactly the same terms with exactly the same meaning. Recently, I even discovered that some UK university that teaches ER modeling, uses the term "entity subtype" for the very same thing that I always used to name "entity supertype", and vice-versa !
One could use connection.
You have Connection between two tables, where the IDs are the same.
That type of thing.
how about
Association
Link
Correlation

Resources