I have been set the task of creating 3 tables in MySql. One table called subjects with a field called subject_id as the primary key, another table called students with a field called student_id and a final table called entries.
The entries table must have two foreign keys, subject_id and student_id.
This is the official task:
Can anyone possibly help?
In your create table query after you define the column that will be your foreign key, simply write "Foreign Key - References -" and specify the column (where I wrote the first dash mark) you wish to connect to the other table. The second dash should be the table name followed by the column it references in parentheses.
If the table is already made, just use an alter table query and write "add foreign key - references -" with the same format as above.
Something like this
CREATE TABLE Subjects (
SubjectId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (SubjectId))
CREATE TABLE Students (
StudentId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (StudentId))
CREATE TABLE Entries(
EntriesId INT NOT NULL AUTO_INCREMENT,
SubjectId INT NOT NULL,
StudentId INT NOT NULL,
FOREIGN KEY (SubjectId) REFERENCES Subjects (SubjectId),
FOREIGN KEY (StudentId) REFERENCES Students (StudentId))
Related
Which is better method among below:-
Using unique column name for each column, primary and foreign keys among all table.
Example 1:
CREATE TABLE projects (
project_id PRIMARY KEY,
project_name VARCHAR(30)
client_id INT,
fk_project_user_id INT, ( FOREIGN KEY )
projects_created_by INT, ( FOREIGN KEY )
);
CREATE TABLE clients (
client_id PRIMARY KEY,
client_name varchar(20),
fk_client_user_id INT,( FOREIGN KEY )
client_created_by INT, ( FOREIGN KEY )
)
Don't care about the uniqueness of each column name for each primary and foreign keys among all tables.
Example 2:
CREATE TABLE projects (
id PRIMARY KEY,
project_name VARCHAR(30)
client_id INT, ( FOREIGN KEY )
fk_user_id INT, ( FOREIGN KEY )
created_by INT ( FOREIGN KEY )
);
CREATE TABLE clients (
id PRIMARY KEY, (Same as above table)
client_id INT,
client_name varchar(20),
fk_user_id INT, ( FOREIGN KEY ) (Same as above table)
fk_client_id int, ( FOREIGN KEY )
created_by INT ( FOREIGN KEY ) (Same as above table)
);
When we plan database for big ERP having multiple tables and relationships among all? I have used a different name for each key to avoiding ambiguous error when we join two tables.
What is the best solution?
Naming conventions are up to you. Which naming convention you decide to use is not important. What's important is that you follow your own convention consistently, and document it so that other developers know how to understand your code and your schema.
Some people choose to give every table a primary key named id. If every one of their tables must have a column named id, then they can write reusable code for certain queries against any table.
However, this convention does not account for compound primary keys. Also if your query does a join, the query result set may have multiple columns named id unless you define column aliases.
When I design a database, I name my primary key in a descriptive way. projects.project_id for example. This avoids the problem of duplicate column names in a result set of a join. It also makes it more clear what the column means when you see it in a query or a result set.
I like to name the foreign key the same as the primary key column it references, when I can do it without resulting in a conflict.
But consider this example, where there are multiple foreign keys in the same table that reference Users.user_id.
CREATE TABLE Bugs (
bug_id INT PRIMARY KEY,
description TEXT NOT NULL,
reported_date DATETIME NOT NULL,
user_reported_by INT NOT NULL,
user_assigned_to INT,
user_verified_by INT,
FOREIGN KEY (user_reported_by) REFERENCES Users(user_id),
FOREIGN KEY (user_assigned_to) REFERENCES Users(user_id),
FOREIGN KEY (user_verified_by) REFERENCES Users(user_id)
);
You can't assume you can use a common column name, because it's normal to need multiple foreign keys referencing the same table, as in the example above. Therefore you must allow the FK column name to be different from the PK it references.
Is order of execution important when creating Primary/Foreign Key links in a MySQL statement?
For example, the following code will produce the error: "Cannot add foreign key constraint"
CREATE TABLE IF NOT EXISTS Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
Cannot add foreign key constraint
But when the Genre table is created FIRST, the error no longer persists:
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
CREATE TABLE Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
Schema Ready
Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
When I was searching for a solution to foreign key constraints all I found was information on the data type matching, but not the order of execution. Thanks.
Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
Yes.
If you define the Movies table first, MySQL is going to try to find the referenced Genres table, which does not yet exist. So you should create them in the opposite order:
CREATE TABLE IF NOT EXISTS Genres
CREATE TABLE IF NOT EXISTS Movies
Foreign key is a reference to another key: primary key. If primary key doesn't exist now, you can not reference to an unknown thing, so you get exception.
I'm having trouble adding a foreign key field that references another table.
First I created the users table as so:
CREATE TABLE users (
user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
userName VARCHAR(256) NOT NULL,
userEmail VARCHAR (256) NOT NULL,
userPwd VARCHAR(256) NOT NULL,
);
then I'd like the quizzes table to have a foreign key that references the user_id from the first table
CREATE TABLE quizzes (
quizId INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
quizName VARCHAR(128) NOT NULL,
quizMax SMALLINT(6) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
This is throwing the error: 'Key column 'user_id' doesn't exist in table.
Other answers advised to check that DB is InnoDB, which I did, and it is.
Can't understand why it's telling me that user_id doesn't exist, when it clearly does exist in the users table.
Firstly check if table user is created successfully, due to the additional ',' on last column!
Secondly, the column you reffered in FOREIGN KEY(user_id) is not defined in table quizzes, you need to add this column in quizzes table.
First: You do not need the last comma - , in the first CREATE statement. -
Second: you have to create the columns before you can use them in a foreign key constraint and user_id does not exist in the second table at the moment of constraint creation.
Take a look at the example below. The last create succeeds when user_id column is added before the constraint is created:
I have 3 tables:
class_a
CREATE TABLE class_a (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
std_id INT NOT NULL UNIQUE,
name varchar(225) NOT NULL)
class_b
CREATE TABLE class_b (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
std_id INT NOT NULL UNIQUE,
name varchar(225) NOT NULL)
sn_number
CREATE TABLE sn_number (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
pin INT NOT NULL UNIQUE,
serial VARCHAR(255) NOT NULL UNIQUE,
std_id INT NULL DEFAULT NULL,
FOREIGN KEY(std_id) REFERENCES class_a(std_id)
)
How can I reference unique std_id in class_a and class_b table as a foreign key in sn_number table.
I want to achieve something like ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_a(std_id), class_b(std_id)
I have tried doing this ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_a(std_id)
followed by
ALTER TABLE sn_number ADD FOREIGN KEY(std_id) REFERENCES class_b(std_id) on sn_number table but will keep overwriting each other.
I have read these:
Foreign Key Referencing Multiple Tables and
Composite key as foreign key (sql)
But I can't find the solution to the problem am having.
Foreign key must reference only one parent table. This is fundamental to both SQL syntax, and relational theory.
What you can do, is add another table classes or students that contain all std_id , then just reference the FK to it.
Since you haven't explicitly given a constraint name in your FOREIGN KEY declarations, the DBMS makes one up from the table name sn_number. Your problem is that you are thus implicitly declaring the same constraint name each time, so the old info for the name is lost. Just use different explicit constraint names for different cases of table & column list REFERENCES table & column list.
CONSTRAINT fk_sn_number_a FOREIGN KEY(std_id) REFERENCES class_a(std_id)
CONSTRAINT fk_sn_number_b FOREIGN KEY(std_id) REFERENCES class_b(std_id)
Just learn about the basics of Using FOREIGN KEY Constraints.
PS As remarked in a comment, this is a poor design. But contrary to the comment & another answer, your need for two foreign keys from the same table & column list is not a symptom of poor design. But notice that the problems that people usually have with "Foreign Key Referencing Multiple Tables" in questionable designs is that they think that their tables as designed need a foreign key from one place to two places when they don't. Such a design doesn't even involve a foreign key, it just involves something reminiscent of a foreign key.
What would be the code for creating a table with two foreign keys?
I have a USER table and a PICTURE table. Since a USER can be in many PICTURE and many PICTURE can be from a USER, I need a third table with both primary keys.
Thank you SO, as usual you are invaluable for a learning novice. :)
I can't speak specifically for mySQL but in most databases I have worked with you can put as many foreign keys as you need on a table. But you can only have one primary key. A third table with both keys is the right choice. Make a foreign key to each of the other two tables and a primary key consisting of both ids in the table.
If I understood correctly, you may need to do something like the following:
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE=INNODB;
CREATE TABLE pictures (
picture_id INT NOT NULL PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
posted_by INT NOT NULL,
FOREIGN KEY (posted_by) REFERENCES users(user_id)
) ENGINE=INNODB;
CREATE TABLE users_in_pictures (
user_id INT NOT NULL,
picture_id INT NOT NULL,
PRIMARY KEY (user_id, picture_id),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (picture_id) REFERENCES pictures(picture_id)
) ENGINE=INNODB;
Note that each picture can be posted by a user. In fact the posted_by field is constrained by a foreign key that references the users table.
In addition, I assume that you want to tag pictures ala-facebook. In this case, you can use the third table, which is using a composite primary key on (user_id, picture_id) and both fields are also constrained to the appropriate table.