SQL Foreign key for Primary key with 2 values - mysql

As far as I'm aware, you can only assign primary keys and unique columns to foreign keys... yet I have a table that has a primary key between two columns:
alter table NAME add constraint PK primary key(VALUE1, VALUE2)
I'm trying to make Value1 a foreign key in another table, but it's not recognizing it as a primary key or unique - obviously because the primary key is shared between two values... So what do I do from here? I'm pretty new to SQL syntax...

You are correct that you can only assign primary keys and unique columns to foreign keys. I am not much aware of the business requirement here but ideally, you should be having a third table which has the VALUE1 as a primary key. If not you should create one.

The main idea is that you can't link a foreign key to a value that can hold duplicates on the referenced table. So if your main table has a compound key (more than 1 column), linking the foreign key to one (or many but not all) of it's columns would be linking the table to more than one row (since that column might have duplicates by itself).
If you really need to establish the link between the two then you have a problem, either:
Your primary key isn't really 2 or more columns. You can read about normalizing your database (in standard normal forms) to solve this.
Your relationship between the tables isn't 1 to N (it's N to M). You can't add a foreign key, you will have to create a 3rd table with both primary keys to link them.

Related

I want to create multiple tables with the same composite primary key without data redundancy in mysql. How can I achieve this?

I am using mysql to create a database.
I have one base table named GP, with its Primary Key a composite Primary Key(SAT_ID, DATE).
I want to create multiple tables with the same Primary Key (SAT_ID,DATE), but would like to avoid data redundancy.
Is there a way to create a Primary Key for the children tables (for example ID INT NOT NULL AUTO_INCREMENT) that references the composite Primary Key (SAT_ID,DATE), so that I can avoid having the same composite Primary Key (SAT_ID,DATE) in every other table ?
I know the question can seem silly but there is something I don't understand about composite keys and data redundancy.
Thanks
#pepper's solution (suggested in the comments) works just fine:
You could modify your GP table to have an autoincrement ID as PK and
an unique index on (SAT_ID, DATE), then you can use ID as foreign
key in your other tables

Why does mysql allow a foreign key to refer a part of composite primary key?

Suppose I have two tables in mysql
1.Child(name,father_name)
2.Father(name,contact)
The table Father has a composite key (name,contact).Father_name in Child table references name in father . Thus a foreign key references a part of primary key.This is allowed by mysql.
However consider the following situation:
Table father has the following tuples:
(kishan,9906011111)
(kishan,9990601234)
Now suppose I insert a row in child
(xyz,kishan)
How would I know which kishan in the father table is the child xyz related to ?
This situation could have been avoided if mysql does not allow a foreign key to refer a part of the primary key .
Please answer what's the benefit of this scheme allowed by mysql ?
This is a peculiarity of MySQL. In my opinion, foreign keys should only be to unique keys or primary keys. There should not be a mapping to "sets" of values using a foreign key relationship.
Clearly, the designers of MySQL disagree (both with me and other database implementors). They allow foreign key relationships to any columns that are indexed -- in MySQL parlance, are defined as a "key". If you have a composite primary key, then the initial column(s) are such a key.
To prevent problems and make your tables unambiguous and easy to use, I would recommend:
All tables have an auto-incremented primary key.
All foreign key relationships are only to primary keys (not to unique keys or other types of key).
The primary key be named the singular of the entity followed by id (example: things would have thingId as a primary key).
The foreign key have the same name as the primary key (except when this is not possible because there are multiple foreign key relationships to the same table).

Use of Primary Key as Foreign Key in Foreign Key Table

This may sound confusing and or simple but..
If I use a foreign key from Table B in Table A, which has a separate primary key. Do I need to include Table A's primary key as a foreign key in Table B?
Thanks!
========================================================================
EDIT:
Okay, let me try and clarify my question a bit.
In the case above, should I use Taco_ID as a FK in Table 2? Or is does it completely unnecessary?
In general, you don't usually make foreign keys bidirectionally like that. If you do, it means that the two tables exist in a 1-to-1 relationship: Each taco has a type, and each taco type can only be used by one taco. If you have a relationship like this, there's not really any reason to have them in separate tables, they could just be additional columns in the same table.
Normally foreign keys are used for 1-to-many or many-to-many relationships.
A 1-to-many relationship would be if many different tacos can be of the same type. They each have Taco_Type_ID foreign key.
For a many-to-many relationship, you typically use a separate relation table.
CREATE TABLE Taco_Types (
Taco_ID INT, -- FK to Table1.Taco_ID
Taco_Type_ID INT, -- FK to Table2.Taco_Type_ID
PRIMARY KEY (Taco_ID, Taco_Type_ID)
);
foreign keys and primary keys are SOMETIMES related, but not always. A foreign key in a table literally just means "whatever value is in this field MUST exist in this other table over ---> here". Whether that value is a PK or not in that other table is irrelevant - it just has to exist, and it has to be unique. That may fit the bill of being a primary key, but being primary is NOT required.
You can have composite foreign keys, e.g. in a (silly) address book, the child table you list a person's phone numbers in COULD be keyed with (firstname, lastname), but that runs into the problem of "ok, which John Smith does this number belong to?".
In most databases, foreign key references must be to primary keys or unique keys (and NULLs are allowed). MySQL recommends this but does not require it:
However, the system does not enforce a
requirement that the referenced columns be UNIQUE or be declared NOT
NULL. The handling of foreign key references to nonunique keys or keys
that contain NULL values is not well defined for operations such as
UPDATE or DELETE CASCADE. You are advised to use foreign keys that
reference only UNIQUE (including PRIMARY) and NOT NULL keys.
Do you need to reference primary keys for a foreign key relationship? First, you don't even need to declare foreign key relationships. I think they are important because they allow the database to maintain referential integrity. But, they are not required. Nor is there any semantic difference in queries, based on the presence of foreign keys (for instance, NATURAL JOIN does not use them). The optimize can make use of the declared relationship.
Second, if you are going to declare the foreign key, I would recommend using the primary key of the referenced table. That is, after all, one of the major reasons for having primary keys.

How can I link multiple tables in MySQL database other than using primary key-foreign key relation?

I have tables named 'studentdetails', 'class', 'obtainedmarks', and 'subject' in a database.
I have a primary key named 'STUDENTID' in table 'studentdetails' which is connected to other tables as a foreign key.
I want to make one more primary key in the same table 'studentdetails' taking three columns ('STUDENTID','CLASS','ROLLNO') so that I can use the foreign key relation to the three columns of 'obtainedmarks' table.
How can I establish such relation as we can make only one primary key in a table?
Mysql certainly allows foreign key relationships to span multiple columns. In fact there is even a full example in the manual. Thus your relationship might look something like
CONSTRAINT fk_multi FOREIGN KEY (`studentid`, `class`,`subject`)
REFERENCES other_table (`studentid`, `class`,`subject`)
ON DELETE CASCADE ON UPDATE CASCADE,
Note however that what goes into the REFERENCES section is the names of the columns and not the name of the index on that other table.
Getting onto the Primary Key problem, it's true that you can only have one primary key per table. But there's nothing to prevent you from creating a composite unique key on the three columns that are referenced.

Junction table without primary key

Say I have a junction table to resolve a many to many relationship I have between two tables. My junction table also has its own 'Method' column to describe the relationship.
Normally, I would make a composite primary key of [a], [b] and [method] (the method needs to be part of what makes a row unique), but my problem is that [method] field can be NULL. Therefore I cannot add it to the primary key.
So what I've done is create a unique index:
ALTER TABLE A_B ADD UNIQUE INDEX `Unique` (`a`, `b`, `method`);
The table has no primary key. Is this an okay thing to do or do I need to do something differently?
Using a primary key is not the only way to ensure records uniqueness. There is a unique constraint you can implement to accomplish what is needed.
http://www.w3schools.com/sql/sql_unique.asp