This question already has answers here:
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
(4 answers)
Closed 5 days ago.
I have some trouble,
Data Example:
animal_table:
id
name
desc
farmer_table:
id
name
desc
investor_table:
id
name
desc
Main Trouble: now i will create Simple CRUD applications, but there is some conditions.
Investors(Many) to Animals(Many)
Farmers(One) to Animals(Many)
how do i create the database Structure for this problems
The textbook solution to implementing a many-to-many relationship is a mapping table with the IDs of the entities you want to have in the relationship. Each row in this mapping table represents a connection between the two entities. E.g.:
CREATE TABLE investors_animals (
animal_id INT NOT NULL,
investor_id INT NOT NULL,
PRIMARY KEY (animal_id, investor_id),
FOREIGN KEY (animal_id) REFERENCES animal(id) ON DELETE CASCADE,
FOREIGN KEY (investor_id) REFERENCES investor(id) ON DELETE CASCADE
);
In this answer it is shown what you need:
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
For your example it would be something like this:
Investors(Many) to Animals(Many)
You need a need Table like investor_animal:
investor_id
animal_id
Farmers(One) to Animals(Many)
You can give the animal table a farmer_id. So the animal knows who is the farmer.
Related
I have quite simple question. I am creating database administration tool, where user will be able to create relations between tables, but I am not sure if table order is important when creating relations.
For example: I have two tables 'user'(user_id(INT, PRIMARY KEY), name(VARCHAR), email(VARCHAR)) and 'post'(post_id(INT, PRIMARY KEY), content(TEXT), author(INT)).
When user has selected one column from both tables ('user'(user_id) and 'post'(author)) tool creates a query:
ALTER TABLE 'user' ADD CONSTRAINT 'user_id_to_author' FOREIGN KEY ('user_id') REFERENCES post('author')
but if user would select tables in different order ('post'(author) and 'user'(user_id)) then query would look like this:
ALTER TABLE 'post' ADD CONSTRAINT 'author_to_user_id' FOREIGN KEY ('author') REFERENCES user('user_id')
Is there any difference between both query's and if so whats is it?
You are defining a one-to-many relationship, so the direction of the relationship does matter.
The table that is altered is the child table; many rows may refer to the parent table, through the primary key of the parent table.
For the example given here, a post belongs to a user, and many posts may have the same author, so you want:
ALTER TABLE post
ADD CONSTRAINT author_to_user_id
FOREIGN KEY (author) REFERENCES user(user_id)
Note that object names should not be surrounded with single quotes.
Trying to create the relationship the other way around does not make sense. It would imply that a user needs to have a post before it can be created.
As an introductory project for my school subject, I was requested to create an app for showing the list of shops in my country with the possibility to sort it by location and category. What is more, it should not be just a static text, as a user may add his/her own shops to the list.
Although I am not experiencing any problems with the UI and functionality of my Java application, I am a complete newbie to databases and, particularly, to MySQL. Even though I have scrutinized some tutorials, I still keep toiling over one indeed primitive issue.
The problem is:
I created a table "Shop" with columns "id"(the primary key with auto increment), "name"(text type), "type"(text type) and "location"(text type).
Alike, two more tables were made:
1) "Types" which contains "id" again as the primary key and "type". For example:
id type
1 supermarket
2 grocery
3 bookshop
2) "Location" with "id" too and "city". Something like this:
id city
1 London
2 Nottingham
3 Southampton
What I attempted to do is to create "many to 1" relation between "Types"/"Location" and "Shop" tables (or "1 to 1" between "Types" and "Shop" as well as "Location" and "Shop"), because further I would want to sort shops by location and type and, consequently, print list of relevant shops in my app. However, I simply cannot find the logical sequence how to implement those connections.
Looking forward to any tips.
Thanks in advance!
Both of the relationships you describe here are one-to-many:
A shop has one and only one type. A type can be used in many different shops.
A shop has one and only one location. A location can be used in many different shops.
An extra consideration can be made about if you allow a shop to have an empty type or location. For simplicity, we will consider that is not happening here (but it can be implemented by using nullable foreign keys).
One-to-many relationships are implemented by adding a foreign key between the two involved tables. That is made by adding a column in the child table that contains the id (primary key) of the parent table, and creating a foreign key constraint for those columns.
That is, you have to add a typeId column to your Shop table, and define the foreign key constraint in your database. Same for the relationship with locations: add a locationId column to Shop and a foreign key constraint.
You shouldn't include in your Shop table the text columns for location and type names, only the columns for the IDs. When using that information to search you will do queries with joins between the different related tables. Something lke this:
SELECT s.name, t.type, l.city
FROM Shop s
INNER JOIN Types t ON s.typeId = t.id
INNER JOIN Location l ON s.locationId = l.id
WHERE t.type = 'supermarket'
More info about joins here.
The SQL needed for implementing the foreign keys is different if you are creating the tables with the foreign keys already, or if you are modifying your existing tables. This page contains examples of both approaches.
The simple case of creating the table with the foreign keys:
CREATE TABLE Shop (
id int NOT NULL,
name text NOT NULL,
typeId int NOT NULL,
locationId int NOT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_TypeShop FOREIGN KEY (typeId)
REFERENCES Types(id),
CONSTRAINT FK_LocationShop FOREIGN KEY (locationId)
REFERENCES Location(id)
) ENGINE=INNODB;
An important remark: in MySql only the InnoDB storage engine supports foreign keys, so you must create your tables with that ENGINE=INNODB parameter at the end of the SQL command in order to use foreign key constraints. If you don't specify that then the default engine will be used instead of INNODB and your foreign keys will not work. Update: since version 5.5.5 InnoDB is the default engine, so unless the engine has been explicitly changed for your database you don't need the explicit engine parameter.
This page contains a good explanation of foreign keys in MySQL (perhaps too detailed for what you need now, but you can check it for specific information).
As a best practice, name all your tables either in plural or either in singular, but use the same criteria for all. Probably you should rename table Types to Type (or either rename the other two tables to give them plural names).
This table should contain foreign keys to allow sensible links to be made with the other two tables, together with the dates of each exam.
So what am i being asked to do exactly?
All the other tables have been populated.
This looks like a classic Many To Many relational problem.
One student can study more than one subject
A subject can be studied by more than student
This cannot be readily modelled relationally using just the two tables you have given.
The traditional way to model this is to introduce a third table which contains the details of which students are studying which subjects.
The table would generally contain the id's of the tables that participate in the many to many relationship, so in your case it would have student_id and subjects_id. These would be defined with foreign key constraints back to the student and subjects tables.
This page may go a long way to helping you understand this.
By the way - the primary key constraint on the subjects table looks a bit suspect to me ...
First of all, your PRIMARY KEY of the subject table should be subjects_id, because you may have 2 final exams the same day.
CREATE TABLE IF NOT EXISTS entries(
entry_id INT UNSIGNED NOT NULL AUTO_INCREMENT,( PK)
student_id INT UNSIGNED NOT NULL,(FK From students table)
subject_id INT UNSIGNED NOT NULL,(FK From subjects table )
);
You need to make (student_id,subject_id) combination unique since it shouldn't be duplicated.This is rough draft.Assume that this table is a bridge which connects students and subjects.
I have the following tables:
CREATE TABLE Salesperson
(
id INT,
name VARCHAR(30),
age INT,
salary INT,
PRIMARY KEY (id)
);
CREATE TABLE Orders
(
Number INT,
ORDER_DATE DATE,
cust_id INT,
salesperson_id INT,
Amount INT,
PRIMARY KEY (Number),
FOREIGN KEY (salesperson_id) REFERENCES Salesperson (id)
);
I would describe the foreign key relationship as a many-to-one, non-mandatory-to-mandatory relationship between the referencing (child) table Orders to the referenced (parent) table Salesperson.
However, MySQL Workbench describes the relationship as a one-to-many, mandatory-to-non-mandatory relationship between the referencing table (child) table Orders to the referenced table (parent table) Salesperson.
Is it me, or MySQL Workbench that has it backward? An explanation would be appreciated.
Update
I found this definition of "Mandatory" under the MySQL Workbench docs:
The Mandatory checkboxes are used to select whether the referencing table and the referenced table are mandatory. By default, both of these constraints are true (indicated by the checkboxes being checked).
The relationship is in both directions. Or, you can think of it as two halves of the same relationship.
A foreign key relationship like this typically called 'one-to-many', rather than 'many-to-one'. MySQL workbench is referring to it using the normative pattern.
FOLLOWUP
Q: why is Orders.salesperson_id mandatory, while Salesperson.id non-mandatory? Salesperson.id is a primary key, and Orders.salesperson_id is not a primary key, so wouldn't the check boxes be reversed?
A: I'm not familiar with the checkboxes in MySQL workbench.
As Mike Lischke points out in his comment, what we're concerned with at the Entity-Relationship modeling level is the "cardinality" of the relationship. Basically, we're asking the questions, Do we require that an Order be related to a Salesperson? That is, can we have an Order that is not related to a Salesperson?
Can we have Salesperson that is not related to an Order?
And obviously we've already answered the questions, can a Salesperson be related to more than one Order? Can an Order be related to more than one Salesperson? That's how we determined that this is a one-to-many relationship. Now we're just further refining the cardinality.
I think the "Mandatory" checkbox in the UI is meant to answer the question: Can we create an instance of Salesperson that is not related to an Order, or do we require a Salesperson to be related to at least one Order?
Again, the questions make sense if we view this as two relationships we're asking questions about. We're asking questions about the relationship from Salesperson to Order, and also about the relationship from Order to Salesperson.
Based on the answers to our questions, we mark Order.salesperson_id as "mandatory" to indicate that we are going to require that an Order be related to a Salesperson. We mark the other direction of the relationship as "non-mandatory" to indicate that we are not going to require that a Salesperson be related to an Order.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
MySQL Relationships
I am trying to create a one to many relationship in MySQL with foreign keys.
Two tables, user and location. Each user can have many locations, but each location can have only one user.
How do I configure this? I am using HeidiSQL if that helps, though I can input code as well.
MySQL does not know, nor does it need to know if a relationship is 1-1, or 1-many.
No SQL supports many-many relationships, all require a intermediate table which splits a many-many relationship into 2 separate 1-many.
The difference is in the logic that controls the relationships, which is in the code that you write.
A 1-1 relationship is maintained by having the tables share the same primary key (PK).
With the secondary table declaring that PK as a foreign key pointing to the other tables PK.
Table chinese_mother (
id integer primary key,
name....
Table chinese_child (
id integer primary key,
name ....
....,
foreign key (id) references chinese_mother.id
The direction of the relationship 1 -> many vs many <- 1 is determined by the location of the link field.
Usually every table has a unique id and the link field is called tablename_id.
The table that has the link field in it is the many side of the relationship, the other table is on the 1 side.
Each user can have many locations, but each location can have only one user.
Table user
id: primary key
name......
.....
Table location
id: primary key
user_id foreign key references (user.id)
x
y
.......
By placing the link field in the location table, you force things so that a location can only have 1 user. However a user can have many locations.
There is an example here that is almost exactly what you need foreign keys in innodb
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
In your example user is the same as parent (a user has many locations, a parent has many childs) and location is the same as child (a location has one user, a child has one parent)