MySQL style for creating foreign key - mysql

I've searched a bit for this, but I actually haven't found what is the style conception in MySQL for creating a foreign key - in the create table definition or in an alter statement. Thank you.

When to create foreign key:
If at the time of table creation it is clear you that you need foreign key then do at the time of creation, but if you realize later then do it in alter.
Best practices: you can follow below practice, it is not must but you can get benefits-
constraint fk_tableName_colName foreign key (colName) references parent_table(referenced_col_Name) cascading if required
Note: As foreign key name must be unique, so it will help to maintain it.
Points Need to remember:
referenced table in parent table must be indexed (if primary key then no need as it will be indexed).
column in both tables (parent/child) must have same schema.

Have a look at the docs on how to create foreign keys...
http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
When a foreign key gets added can be during the initial architecture of the application being built or it can be added later as the application evolves.

Related

Is it valid to have a foreign key that references a partial primary of another table?

I've been researching whether it's valid to have a foreign key that refereces a partial primary key of another table.
From several sources (see below), it seems like it's not valid, however, it works perfectly fine using MySQL.
Is this behavior specific to MySQL, or is it valid to have a foreign key that references a partial primary key in general?
I would appreciate a link to some documentation that confirm any claims.
A FOREIGN KEY is a field (or collection of fields) in one table that
refers to the PRIMARY KEY in another table.
https://www.w3schools.com/sql/sql_foreignkey.asp
Partial foreign key reference. A foreign key must refer to an entire
primary key, and not just part of it
https://www.dataversity.net/primary-key-and-foreign-key-errors-to-avoid/
This behaviour is storage engine specific in mysql. As mysql manual on foreign key constraints says:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are the first columns in the same order.
Hidden columns that InnoDB adds to an index are also considered (see
Section 15.6.2.1, “Clustered and Secondary Indexes”).
NDB requires an explicit unique key (or primary key) on any column
referenced as a foreign key. InnoDB does not, which is an extension of
standard SQL.
Despite innodb allowing this behaviour, I do not suggest you to go down this route because questions the exact relationship between the two tables. Always link to the entire primary or unique key.

PRIMARY KEY and FOREIGN KEY to my table

So im trying to add an primary key and a foreign key to my table, but i just can't seem to get it to work. i've checked the forums already and other places but it didn't answer my problem. So here is my table:
http://puu.sh/mVW7D/5986e08daa.png
im trying to get VeiederID as my foreing key and keep studentnr as primary
but ive tryied to "alter table" and add the foreing key as constraint, but i might be doing it wrong, im very new to mysql. any help is appirciated
Steffen
Two points:
You do not identify the second table. A foreign key works between two tables and you are only showing one.
You do not specify which mysql version you are using.
Regardless: You should read the manual, reference: v 5.7 Foreign Keys
Update
I see from your updated example you are creating 3 tables and you want the rows in Veileder to reference studentinfo. So, the statement in the Veiled table should be
FOREIGN KEY (VeilederID)
REFERENCES studentinfo(VeiederID)
ON DELETE CASCADE
Apologies if the spelling is wrong. One other note, it appears you are trying to make the primary key (VeilederID) map to the foreign key. If I am wrong please comment but I don't know if that would be allow. Typically a table HAS it's own primary and a reference constrain (a.k.a. FOREIGN KEY) as a different column.
think i found it now i dont get an error while im running it this way, but if its right im not sure..
http://puu.sh/mW1Ze/ae333a40d6.png

Setting foreign key in phpMyAdmin

I want to make namecon of table "paper" as a foreign key reference to table "journal" to its primary key jname. I am getting confused with this view and not finding any tutorial or link which is explaining to set foreign key with this schema of phpMyAdmin. (Is it new or what)
Please someone let me to figure this out.
First, you need to create an index on the namecon column, click on the Structure tab ("Table structure" sub-heading on newer phpMyAdmin versions), then the Index text for the namecon column. You also need an index on the jname column in your journal table; in most of my databases this is an auto incrementing primary key but all that MySQL requires is that it's an index.
Next, go back to the Relation View (which is a sub-heading of Structure under newer versions). Note that this is in the area for "Foreign key constraints" not "Internal relations." Now you'll be able to select namecon from the "Column" dropdown:
If you want you can give it a name, otherwise MySQL generates one for you.
While making the foreign key, it is also advisable to mark the index key option available int Structure view of the table.
That will make the primary key thing to visible in the relational view of that particular table which can be used for making foreign key.

Documentation says CakePHP does not support composite keys

In the "conventions page" it says (caution noob here):
"CakePHP does not support composite primary keys. If you want to directly manipulate your join table data, use direct query calls or add a primary key to act on it as a normal model. "
I am very confused by this statement. Composite keys are very basic and form many database structures with identifying relationships.
I am developing my schema and am trying to get around using composites, but it is impossible.
How does this work exactly?
CakePHP expects you to have set up a database. You must use certain naming conventions. You then describe it to your CakePHP code via a configuration file.
The database should have its primary keys, alternate candidate keys, foreign keys and constraints as appropriate. But the quoted line is telling you to make sure that every table has a one-column primary key. So this means that where you wouldn't already have such a primary key you add a column, make it the primary key, and declare what were the primary key columns as UNIQUE NON NULL (which is what PRIMARY KEY does), ie as an alternate candidate key.
You should also add any appropriate new versions of constraints including new foreign keys. Note that the old foreign keys can just stay as they were since an SQL FOREIGN KEY declaration only needs to reference a unique field, not a primary key per se. (Ie it's really a foreign superkey declaration.) You should also constrain such new+old foreign key pairs in a table to actually be be a valid pair of values in the referenced table, ie declare the combined columns to be a foreign key to the combined columns as unique. (Ie you don't just want both primary & alternate key values to be in the referenced table, you want them to be there together.)

What is the meaning of self referencing foreign key?

I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
What is the meaning of it?
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.
In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)
As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.
In some cases this is a preferred way to reduce redundancy in your model. In using the self referencing foreign key (as shown in you example) you create a hierarchical relationship between rows in your table. Pay attention to what happens when you delete a row from the table, cascading on delete might remove rows you still want.
Using these sort of keys moves some of the data validation to the DB model as opposed to making this a responsibility of the program/programmer. Some outfits prefer this way of doing things. I prefer to make sure programs and programmers are responsible - data models can be hard to refactor and upgrade in production environments.