MySQL How to create one to Zero or Many relation - mysql

i have entity customer and entity order, a customer can have 0 or more orders but an order can only have 1 customer.
I already tried a lot of things like making the foreign key unchecked at NN but I cant get a foreign key order at customer
EDIT: Using mySQL ERD workbench

Your customer table will have a unique customer_id column. In the MySQL world we often use autoincrementing primary keys for this kind of id column.
Your order table will have a customer_id column that's a foreign key to customer.customer_id.
This allows the order table to have any number of rows relating to a particular customer_id: none, one, or many. The foreign key relationship, when enforced--checked--simply prevents an order from having a customer_id value that references no valid customer.
Classic data design tools with their distinction between logical and physical design can drive ya nuts when you're trying to do easy stuff like this.
Pro tip if you name your id columns the same way everywhere they're used, data design tools tend to work better, especially when "reverse-engineering" your tables. That's why I suggested column names like customer.customer_id and order.customer_id rather than customer.id and order.customer_id.

Related

Can A Foreign Key Be Used More than Once?

Apologies for the newbie question.
The primary key of a table, such as Holiday, would be something like Holiday_ID. Holiday reference a get-away ticket that you can buy to go on a type of holiday, based on the ticket you buy.
Suppose I used Holiday_ID in a composite entity with Customer_ID to identify an instance of Holiday associated with customer, for whatever purpose.
However, suppose I also want to keep track of other information related to this instace: how much has the customer paid for the ticket, how much has the customer yet to pay for the ticket
I have two options:
a) I can create another composite entity. However, I am not sure if I can do that because I am not sure if you can use a particualr foreign key more than once
b) I can create a composite/associate entity, however, I am not sure if you can create a composite entity with more than two foreign keys?
To answer the technical parts of your question, once you create a composite unique or primary key, ONLY ONE record in the table can have the same values in the set of fields defined in that key. SO, no, you cannot reuse the holidayId key WITH THE SAME customer. You can use it with another, different customer if you wish.
Second, there is no limit to the number of attributes that can be included in a Unique or primary key. If you need, and if it's appropriate and conforms to the rules of normalization, the key can include all the attributes of the table.
Third, to answer your question below, Any column, or set of columns in a table can be defined as a Foreign Key, as long as it is also the primary key or unique key of some table in the database. And there can be any number of FKs defined in a table, they can even overlap. (you can have HolidayId as a FK, and also have HolidayID and CustomerId as a composite FK) the only restriction is that the FK must reference a Primary or Unique Key of some table in the database.(It can also be the same table the FK is in as well, as when you add a supervisorId to an employee Table that is a FK to the EMployeeId of the same employee table)
This example illustrates one of the problems of using surrogate keys without also using a natural key. to wit, what, exactly is a "Holiday"? Is Christmas 2016 the same "Holiday" as Christmas 2015? Is Christmas in Aruba the same holiday as Christmas in Hawaii?
and then, about the composite table to identify associations of customer with Holiday, is it the same association if the customer goes to Aruba on Christmas the next year, or a different instance? What does the row in the table represent if the customer wants 5 tickets?
The first thing that should be done in database design is a logical design which defines, as clearly and unambiguously as possible, in business terms, the meanings of the entities for each table in the database.

How are these tables related?

Say I run an online business where you can order products from my website, and I have a database with two tables:
Table order with the fields order_number, customer_ID, address
Table customer with the fields customer_ID, first_name, last_name
To get a full, detailed 'report' of the order, I would perform a LEFT JOIN to concatenate data from the order table to include the customer's first and last names along with their address and order number.
My question is, how are these tables related? Are they at all? What would an entity relationship diagram look like? Separately they don't seem to interact and act more like lookup tables for each other.
An order would always have a customer, no? So it is not a left but inner join.
What links them is the customer_id. So your SQL is simply:
select o.order_number, o.customer_ID, o.address,
c.first_name, c.last_name
from orders o
inner join customer c on o.customer_ID = c.customer_ID;
Entity relationship:
Order Customer
Customer_Id 0...N >---+ 1 Customer_Id
... ...
This EF relation is from MS SQL Server's sample database Northwind. In that sample database, just like yours, there are Customers and Orders. Customers and Orders tables are related via the CustomerId fields in both tables (it is the primary key in Customers, and foreign key in Orders table). When you model that as an Entity relation than you have the above diagram. Customer entity have an "Orders" navigation property (via customerId) that points to a particular Customer's Orders. And Order entity have a navigation property that points to its Customer (again via CustomerId). The relation is 1 to 0 or many (1 - *), meaning a Customer might have 0 or more Orders.
When you do the join from Customer's side, you use a LEFT join "if you want to see all Customers regardless they have Order(s) or not" - 0 or more Order(s). If you want to see only those with Order(s) then you use an inner join.
When you do the join from Orders' side, then an Order must have a Customer so it can't be a LEFT join. It is an INNER join.
You can check the relation from both sides using the connecting CustomerId field.
You wouldn't have a separate table for "OrderId, CustomerId" as it is not many-to-many relation (it would be pure redundancy and would create normalization anomalies).
Hope it is more clear now.
In the entity-relationship model, we don't relate tables. Instead, we relate entities which are represented by their key values. In your example, the customer entity (represented by customer_ID) has a one-to-many relationship with the order entity (represented by order_number) and this relationship is recorded in the order table (where order_number is associated with customer_ID). If we were to strictly follow the ER model, we would record (order_number, customer_ID) (a relationship relation) in a separate table from (order_number, address) (an entity relation).
If there's a foreign key constraint on order.customer_ID referencing customer.customer_ID, that's a subset relation that ensures that every order's customer is a known customer. Thus, the relation between the tables and the relation between the entities is not the same thing.
The relational model allows us to relate (join) tables in any way we need. The obvious join for your example would be on the shared domain customer_ID, but I could just as easily find orders which contain a customer's last_name in its delivery address.
An ER diagram for your example could look like this:
My question is, how are these tables related? Are they at all? What
would an entity relationship diagram look like? Separately they don't
seem to interact and act more like lookup tables for each other.
When dealing with data modeling in an ER-Diagram, more in the conceptual model, we should never start thinking of tables, primary keys, foreign keys and stuff as this is for the later model to the conceptual model, the logical model.
By modeling entities in ER-Diagram, we must always recognize them by their attributes/properties. The entities become concrete when we can find properties in them. I feel a lack of context here, so I'll proceed with a guess:
If you need to persist products in your database, and you need to
save the attributes/properties of them, then we have a Products
entity.
If you need to persist clients/users in your database along with
their properties/attributes, then we have a Customers entity.
According to what you said, customers are able to purchase products. So, you have to relate these two entities in any way. With this in mind, stop and think about the following:
You need to persist purchases/orders.
Purchases/orders show which users bought which products.
By linking products and customers, what would we get? The purchasing/orders event, right?
We would then have two entities relating to each other forming the purchasing (or "orders", you name it) event. This event is formed by the need for the present business rules (your rules). You as modeler you need to persist the orders, and you know that products and customers relate in some way, so you can create a relationship between the two entities representing the orders event.
As has been well discussed in other answers, there is the need of separation of attributes here. If the field "address" is where a user lives, not where the product will be delivered, then this attribute must exist in the Customers entity.
If this field/attribute/property is the final location of delivery, it should remain in the relationship orders created between the two entities, customers and products.
Let's talk now about cardinality. If a customer can purchase/order more than one product, and the same product can be purchased by more than one user, then we have a N-N relationship here. I believe this is your case.
Based on everything that was said, we find the following conceptual model:
By decomposing this model, and developing the logic model, we would have:
Now, for what reason we end up with this kind of model?
Relations N-N allow the existence of properties/attributes (if needed), so we can have attributes/properties in the relation Orders, resulting in an ORDERS table with the fields shown. This table represents the purchases/orders made by users/customers.
And for what reason the existence of "Products from orders"?
We need to say what products were purchased in which purchases/orders, especially showing how many of the same type are acquired. In N-N relationships, some properties induces the appearance of new relations which become tables later. In such situations, it is the discretion of the modeler.
In "Products from orders" entity we have a composite primary key, represented by foreign keys.
With this type of model, you can see:
Which users made purchases/orders.
Which purchases/orders were made by which users.
Which products belong to which purchases/orders.
Which products have been acquired by which users.
How many products of a type were purchased/ordered.
Using the date field, you can find out how many purchases were made in periods:
Weeks.
Months.
Years.
Quarters.
Etc.
If you are interested, see also:
E-R diagram confusion
If you have any questions, please comment and I will answer.I hope I've helped a bit.
Cheers.
"Related" is a vague and confusing term. This is because "relationship" gets used in two different ways: as "association" (between values) and as "foreign key" (between tables).
You do not need to know anything about how tables are "related" by foreign keys or common columns in order to query. What matters is how values in a query's result rows are related/associated by the query. The important relationships/associations are (represented by) the tables.
From a relational perspective, there would be a foreign key from Order referencing Customer on customer_id.
A Chen-style ER diagram would have Order and Customer entity types (boxes) and an Orders relationship type (diamond) with participations (lines) from Orders to Order and to Customer. It would have a table for each type. This is an example of perfectly sensible relational design that the ER model, with its artificial and perverse distinction between entities and relationships, cannot capture. People will use a database design like yours to implement such an ER design, though. Even though the ER design isn't, then, the design.
--
When using a database, values are used to identify entities or as property names and magnitudes. Each base table holds the rows of values that participate in some relationship/association given by the DBA. Each query result holds the rows of values that participate in a relation/association that is a combination of conditions and the relationships/associations of the base tables it mentions. All you need to know to query is the relationships/associations of tables.
Order -- order ORDER_NUMBER is by customer CUSTOMER_ID to address ADDRESS
Customer -- customer CUSTOMER_ID is named FIRST_NAME LAST NAME
Order JOIN (Customer WHERE FIRST_NAME='Eddie')
-- order ORDER_NUMBER is by customer CUSTOMER_ID to address ADDRESS
AND customer CUSTOMER_ID is named FIRST_NAME LAST NAME
AND FIRST_NAME='Eddie'
Sometimes values for a list of columns in a row of one table must also appear as values for a list of columns in another table or that table. This is because if the listed values and others satisfy one table's relationship/association then the listed values and yet others will satisfy the other table's relationship/association.
/* IF there exist ORDER_ID & ADDRESS satisfying
order ORDER_NUMBER is by customer CUSTOMER_ID to address ADDRESS
THEN there exist FIRST_NAME & LAST_NAME satisfying
customer CUSTOMER_ID is named FIRST_NAME LAST_NAME
*/
FOREIGN KEY Order(customer_id) REFERENCES Customer(customer_id)
This means that those particular tables and column lists satisfy the (one and only) relationship/association "foreign key in this database". (And a database will have a meta-data table for its foreign key relationship/association.)
We say that "there is a foreign key" from the first table's list of columns to the second table's list of columns. There's only one foreign key relationship/association for the database. When there is a foreign key its tables and column lists satisfy this database's foreign key relationship. But a foreign key isn't a relationship/association. People call foreign keys "relationships", but they are not.
But foreign keys don't matter to querying! (Ditto for any other constraint.) A query's result holds rows whose values (entity & property info) are related/associated by that query's relationship/association, built from conditions and base table relationships/associations.

Is it necessary to bring the primary key of non repeating table while normalizing the database from UNF to 1NF

My UNF is
database(
manager_id,
manager_name,
{supplier_id,
supplier_name,
{order_id,
order_quantity}}
{purchase_id,
purchase_date}
Here manager_name, supplier_id, order_id and purchase_id are primary key.
During normalization there will be 1 table called purchase. Is it necessary to make manager_name as a foreign key?
How can I normalize these database?
This is a part of my college project on database. Normalization is really confusing.
First consider splitting things out by things that naturally go together. In this case you have manager information, supplier information, order information and purchase information. I personally would want to know the difference between an order and a purchase because that is not clear to me.
So you have at least four tables for those separate pieces of information (although depending on the other fields you might need, suppliers and managers could be in the same table with an additional field such as person_type to distinguish them, in this case you would want a lookup table to grab the valid person type values from). Then you need to see how these things relate to each other. Are they in a one to one relationship or a one-to many or a many to many relationship? In a one-to one relationship, you need the FK to also have a unique constraint of index to maintain the uniqueness. In a many to many you will need an additional junction table that contains both ids.
Otherwise in the simplest case the child table of purchase would have FKs to the manager, supplier. and order tables.
Manager name should under no circumstances be a primary key. Many people have the same name. Use Manager ID as the key because it is unique where name is not. In general I prefer to separate out the names into First, middle and last so that you can sort on last name easily. However in some cultures this doesn't work so well.

Beginner Database architecture

I am converting a spreadsheet to a database but how do i accommodate multiple values for a field?
This is a database tracking orders with factories.
Import PO# is the unique key. sometimes 1 order will have 0,1,2,3,4 or more customers requiring that we place their price tickets on the product in the factory. every order is different. what's the proper way to accommodate multiple values in 1 field?
Generally, having multiple values in a field is bad database design. Maybe a one to many relationship will work in this scenario.
So you will have an Order table with PO# as the primary key,
Then you will have a OrderDetails table with the PO# as a foriegn key. i.e. it will not be designated as a primary key.
For each row in the Order table you will have a unique PO# that will not repeat across rows.
In the OrderDetails table you will have a customer per row and because the PO# is not a primary key, it can repeat across rows. This will allow you to designate multiple customers per order. Therefore each row will have its own PriceTicketsOrdered field so you can know per customer what the price is.
Note that each customer can repeat across rows in the OrderDetails table as long as its for a different PO# and/or product.
This is the best I can tell you based on the clarity of your question.
Personally, I normally spend time desinging my database on paper or using some drawing software like visio before I start implementing my database in a specific software like MySql pr PostgreSql.
Reading up on ER Diagrams(Entity Relationship diagrams) might help you.
You should also read up on Database normalization. Probably you should read up on database normalization first.
here is a link that might help:
http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561

Can a foreign key act as a primary key?

I'm currently designing a database structure for our team's project. I have this very question in mind currently: Is it possible to have a foreign key act as a primary key on another table?
Here are some of the tables of our system's database design:
user_accounts
students
guidance_counselors
What I wanted to happen is that the user_accounts table should contain the IDs (supposedly the login credential to the system) and passwords of both the student users and guidance counselor users. In short, the primary keys of both the students and guidance_counselors table are also the foreign key from the user_accounts table. But I am not sure if it is allowed.
Another question is: a student_rec table also exists, which requires a student_number (which is the user_id in the user_accounts table) and a guidance_counsellor_id (which is also the user_id in the user_accounts) for each of its record. If both the IDs of a student and guidance counselor come from the user_accounts table, how would I design the student_rec table? And for future reference, how do I manually write it as an SQL code?
This has been bugging me and I can't find any specific or sure answer to my questions.
Of course. This is a common technique known as supertyping tables. As in your example, the idea is that one table contains a superset of entities and has common attributes describing a general entity, and other tables contain subsets of those entities with specific attributes. It's not unlike a simple class hierarchy in object-oriented design.
For your second question, one table can have two columns which are separately foreign keys to the same other table. When the database builds the query, it joins that other table twice. To illustrate in a SQL query (not sure about MySQL syntax, I haven't used it in a long time, so this is MS SQL syntax specifically), you would give that table two distinct aliases when selecting data. Something like this:
SELECT
student_accounts.name AS student_name,
counselor_accounts.name AS counselor_name
FROM
student_rec
INNER JOIN user_accounts AS student_accounts
ON student_rec.student_number = student_accounts.user_id
INNER JOIN user_accounts AS counselor_accounts
ON student_rec.guidance_counselor_id = counselor_accounts.user_id
This essentially takes the student_rec table and combines it with the user_accounts table twice, once on each column, and assigns two different aliases when combining them so as to tell them apart.
Yes, there should be no problem. Foreign keys and primary keys are orthogonal to each other, it's fine for a column or a set of columns to be both the primary key for that table (which requires them to be unique) and also to be associated with a primary key / unique constraint in another table.