Duplication entry at foreign key column - mysql

I have referenced a foreign key to a primary key. Whenever I click on create new project, I am storing the project Id in the reference key but I want to store multiple projects.
Can anyone please help?

Even your query is not much clear that what issue you are getting but you can understand foreign key concept as per below-
If you create a foreign key in any child table and referenced it with master table means you are saying that child table can contain a value only its reference exists in parent table.
Normally in mostly cases we want to use normalization and basic concept is that we keep unique value in master table (mostly primary key) and its child rows (multiple) in its child table.
Suppose we have two tables customer and order then customer table contains unique customer but as same customer can order multiple times, so order tables may contains multiple customers.
In your case whenever you will create a new project then a new project_id will insert in master i.e. project table and its multiple sub-attributes in its child tables. Now whats the issue you are facing. Please explain.

Related

How to map data between tables when they are connected by foreign key in mysql?

I have a table for resources which contains resources like case studies, whitepapers, webinars etc.
It has one to many relationship with another table case_study_blocks. So there is a foreign key caseStudyId in the case_study_blocks table, which points to case studies in the resources table.
I want to move all the case studies to a separate table case_studies, but to do that I'll also have to update the foreign key reference in the case_study_blocks table and make all the records there point to the newly generated unique ids in case_study table.
What is the correct way to migrate the complete data while preserving the relationship?
One way I can think of:
Drop foreign key constraint on case_study_blocks
Add new foreign key constraint on the caseStudyId column, pointing to the id column in case_studies table
But now how do I map the existing case_study_blocks correctly to the new IDs in case_studies table?
Perform the steps as follows:
Copy the relevant data (related to case studies) to the new case_studies table, including the original ID value -- which could be called oldCaseStudyId -- so that the case_studies table will have the newly generated ID (caseStudyId), and the original ID in a separate oldCaseStudyId column. The latter can be dropped when all is done.
Drop the existing foreign key constraint on case_study_blocks.caseStudyId
Perform the update of the caseStudyId values by the mapping that is now available in case_studies (it has both the old and new ID values). The SQL statement could look something like this:
update case_study_blocks
inner join case_studies on case_studies.oldCaseStudyId = case_study_blocks.caseStudyId
set case_study_blocks.caseStudyId = case_studies.caseStudyId;
Create the replacing foreign key constraint on case_study_blocks.caseStudyId
Delete the original rows from resources that relate to case studies
Drop the column case_study_blocks.oldCaseStudyId

Is table order imporant in mysql when creating relation between them?

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.

Foreign Key Multi Table Possibility

I have seen similar posts and have not found a definitive answer.
I have a series of tables that store data about certain events. Each of these tables have the same structure. Each of these tables has a foreign key constraint for an id showing what item the data is related to.
Each of these tables id structure is also the same CHAR(24). The tables these ids come from must remain separate because they are all completely different.
I am interested in combining all of my data tables into one with a foreign key being constrained to one of 3 tables. So, a row in my data table will have to have an id that is present in one of the three tables. Additionally this foreign key will need the possibility of ON DELETE settings. Is this possible? And to that, is this poor design?
Items A
- id
- ...
Items B
- id
- ...
Items C
- id
- ...
Data
- id FK
No. What you're describing is sometimes called polymorphic-associations but it should be a clue that it's not good design because you can't make a foreign key constraint for it. That is, the FOREIGN KEY syntax only allows you to reference one table, not three.
The only way you could make a real foreign key constraint that performs ON DELETE actions is to make three separate foreign keys:
Data
- idA FK
- idB FK
- idC FK
For a given row in Data, presumably only one of these three foreign keys would be non-NULL. The other two would be NULL. Ensuring this could be done in a trigger or CHECK constraint, or else you would just have to implement it in application logic (i.e. don't insert a row with more than one of these columns non-NULL).
Polymorphic associations, that is storing a single column that may reference one of three different tables, is not a valid relational design.
You can see past answers I've written about polymorphic associations: https://stackoverflow.com/search?q=%5Bpolymorphic-associations%5D+user%3A20860

In a one to one or one to many relationship in a database, which table must have the foreign key?

Sorry If my question seems too obvious but I still can't find the logic between a relationship of a database model.
ONE TO ONE:
If I have a customer that has only one address where do I have to put my foreign key ?
I first thought it would be a good idea to put it on the customer's table; one column with a foreign key referring to an id of an address.
Because if I need to create a customer, first I would need to create an address.
But I have found some example on the internet
, where they put a foreign key in the address' table, referring to an id of a customer
ONE TO MANY :
And the same question would apply if a customer can have multiple addresses, in which table, should I put my foreign key ?
The foreign key goes on the "many" side.
For example, if a sales_order is associated with at most one customer, and a customer can have zero, one or more sales_order
Then we put customer_id in the sales_order table, as a reference to the (unique) id column in customer table.
This means that we will first need to add a row to customer before we can add a sales_order for that customer. (The foreign key constraint will prevent us from adding a row in sales_order that has a value in customer_id column that doesn't exist in id column of customer.
--
For the special case of a one-to-one relationship, we can implement that the same way as a one-to-many, with an additional UNIQUE constraint on the foreign key column. It really comes down to deciding which direction of the relationship is mandatory, and which is optional. Basically, which table will we add a row to first? The table where we add rows later will have the foreign key constraint referencing the table that we previously added a row...

Mysql Foreign Key must reference entire primary key of parent table?

I'm working on a small pizza delivery website and I ran in to a small problem with the MySQL tables.
I found this on Stackoverflow: https://stackoverflow.com/a/10322293/80907
It mentions the following:
Both tables have to use the INNODB engine.
"In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. "
The first isn't really a problem, but the second rule is where I'm scratching my head.
This is a website where you can order pizzas, so I'm saving all data on the users and their order in the database.
Here's a screenshot of what I'm about to write out:
So I'll have a "Users" table and an "Orders" table. The Users will have to have a one-to-many relationship to Orders. Simply put, the order is identified by the user who created it. So it's one-to-many, identifying.
This means that the "Orders" table will have a foreign key, such as "Users_id".
The problem arises when you have to make a table for the many-to-many relationship between the Pizzas table and the Orders table.
This table, let's call it "Order_Details"(MySQL Workbench automatically called it "Orders_has_Pizzas") must reference both "Orders" and "Pizzas".
Now, since "Orders" already references the Users table in an identifying relationship, that's part of the primary key of "Orders".
And let's get that rule out once again:
"In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. "
What this means is that you must reference the entire primary key. If I delete the "Order_Users_id" key, I'll get a 1005 error upon trying to create the database.
My question is simply: is there a way around this? Because as it is right now, I have that User id mentioned in 3 different tables.
Or, am I not understanding it properly and is it indeed necessary to do this for the sake of not having to query different tables for that data?
EDIT: People seem to disagree with me on the relation between Users and Orders being identifying.
I don't see how an individual order can be identified without knowing the id of the user. After the order is made, someone is going to have to deliver the pizza, meaning they'll need to know where to deliver it. That data is in the Users table. Therefor, the Users_id is part of the identity of a single order.
That's how I see it anyway. If I'm wrong, please explain why.
EDIT 2: Thanks to a_horse_with_no_name for clarifying the concept of "identity" in terms of databases, I see the error of my logic now. Info can be found in the comments.
To answer your original question, no, InnoDB foreign key constraints are not required to reference the entire primary key of the referenced table.
In other words, both of the following work in InnoDB:
mysql> ALTER TABLE Orders_has_Pizzas ADD FOREIGN KEY (Orders_id)
REFERENCES Orders (id);
Query OK, 0 rows affected (0.63 sec)
mysql> ALTER TABLE Orders_has_Pizzas ADD FOREIGN KEY (Orders_id,Orders_Users_id)
REFERENCES Orders (id, Users_id);
Query OK, 0 rows affected (0.02 sec)
In fact, InnoDB allows a foreign key to reference any indexed column, even if it's not part of the primary key:
mysql> CREATE TABLE Foo (fooid INT PRIMARY KEY, nonunique INT, KEY (nonunique));
Query OK, 0 rows affected (0.05 sec)
mysql> CREATE TABLE Bar (barid INT PRIMARY KEY, foo_nonid INT, FOREIGN KEY (foo_nonid)
REFERENCES Foo(nonunique));
Query OK, 0 rows affected (0.06 sec)
However, this is not standard SQL and I don't recommend doing it. It means that a row in Bar could reference more than one row in the parent table Foo. Which means a JOIN between these two on the foreign-primary key relationship could unexpectedly create a sort of mini-Cartesian product.
In the Orders table, it's possible for either column of a compound primary key to contain duplicates. Which means a given row in Orders_has_Pizzas could theoretically reference multiple Orders.
As for the question about an identifying relationship, I would agree that Orders has an identifying relationship with respect to Users. That is, it makes no sense for an order to exist with no referenced user.
But in a table where we use an auto-incrementing mechanism to generate unique id's, it seems redundant and unnecessary to add the extra column to the PK. Why would we need Orders to contain the users id? The id alone is guaranteed unique and therefore sufficient to uniquely address each row.
I would say that's a practical choice, whereas the theory would guide us to create the compound primary key in Orders.
It becomes more clear in a many-to-many table like your Orders_has_Pizzas. This table has an identifying relationship with both Orders and Pizzas. The primary key consists of two foreign keys, one referencing Orders and the other referencing Pizzas. There's no need for an auto-increment PK at all.
Some people add a superfluous auto-increment id for many-to-many tables, for the sake of a convention that every table has to have a single-column automatically-generated primary key. But there's no theoretical or practical reason to do this.
CREATE TABLE Orders_has_Pizzas (
id INT AUTO_INCREMENT PRIMARY KEY, -- what is this column for?
Orders_id INT,
Orders_Users_id INT,
Pizzas_id INT,
);