SQL How to Set Foreign Keys - mysql

I need to create 3 tables which look like this
student(sid: CHAR(12), sname: VARCHAR(50), bdate: DATE, address: VARCHAR(50), scity: VARCHAR(20), year: CHAR(20), gpa: FLOAT)
company(cid: CHAR(8), cname: VARCHAR(20))
apply(sid: CHAR(12), cid: CHAR(8))
(Bolded attributes are primary keys)
But I'm not sure how to set the foreign keys since for instance cid of apply table is both primary key in apply table and company table ( which has the same situation for sid between apply table and student table). Thanks for any help.
These are the codes for creating tables:
myQuery = "CREATE TABLE student "
+ "(sid CHAR(12), sname VARCHAR(50), "
+ "bdate DATE, address VARCHAR(50), "
+ "scity VARCHAR(20), year CHAR(20), "
+ "gpa FLOAT) ENGINE=InnoDB;";
myQuery = "CREATE TABLE company "
+ "(cid CHAR(8), cname VARCHAR(20), quota CHAR(8))ENGINE=InnoDB;";
myQuery = "CREATE TABLE apply "
+ "(sid CHAR(12), cid CHAR(8)) ENGINE=InnoDB;";

It looks like the apply table is a many-to-many join between student and company.
In that case, you'd want to set student and company like you have (though posting the output of SHOW CREATE TABLE student may get you more helpful answers). So for the apply table, you want two foreign keys: one on sid which references student.sid, and one on cid which references company.cid. Maybe something like:
ALTER TABLE apply ADD CONSTRAINT sid FOREIGN KEY (sid) REFERENCES student(sid);
ALTER TABLE apply ADD CONSTRAINT cid FOREIGN KEY (cid) REFERENCES copmany(cid);
Edit: Based on your table creation, you're not setting the primary keys either. Add a PRIMARY KEY identifier to any column you wish to be a primary key.

i the apply table set both sid and cid as foreignkeys..this table is called a junction table here the primary key is a composite primary key both sid and cid together.
appply table foreign keys are SID and CID
apply table primary key is (sid,cid) composite primary key.
Each company can have any number of students..
Each student can be part of any number of companies
but one combination wont repeat.

Related

Can a primary key of a subclass table be referenced as a foreign key?

I'm currently working on a mysql project for my class and I'm wondering if the PK-FK of a subclass table can be referenced as FK for another table instead of the PK of the parent class.
Let's say I have the subclass table employees written as:
CREATE TABLE employees (
Person_ID int PRIMARY KEY,
Designation varchar(50),
FOREIGN KEY (Person_ID) REFERENCES persons(Person_ID));
As for the parent class,
CREATE TABLE persons (
Person_ID int NOT NULL AUTO_INCREMENT,
Last_Name varchar(255),
Middle_Name varchar(255),
First_Name varchar(255),
PRIMARY KEY(Person_ID));
Let's say I want to create another table works whose FK references Person_ID from the subclass employees, not the parent class persons.
CREATE TABLE works (
project_ID PRIMARY KEY,
date_started date,
FOREIGN KEY (Person_ID) REFERENCES employees(Person_ID));
Thanks!
Yes, that's technically possible (I guess you tested that already) and is logically also OK in such a case as yours. In fact referencing persons would be wrong if, logically, only employees can take part in the "works on" relation -- the FK constraint wouldn't ensure that they're only employees.
It is no Problem, but you have always check if the id exist.
Ring connection can cause problems.
CREATE TABLE persons (
Person_ID int AUTO_INCREMENT,
Last_Name varchar(255),
Middle_Name varchar(255),
First_Name varchar(255),
PRIMARY KEY(Person_ID));
✓
CREATE TABLE employees (
Person_ID int PRIMARY KEY,
Designation varchar(50),
foreign key (Person_ID) REFERENCES persons(Person_ID));
✓
CREATE TABLE works (
project_ID Int PRIMARY KEY,
date_started date,
Person_ID int,
FOREIGN KEY (Person_ID) REFERENCES employees(Person_ID));
INSERT INTo persons VALUES (NULL,'A','B','C')
INSERT INTO employees VALUES (1,'test')
INSERT INTO works VALUES (1,NOW(),1)
db<>fiddle here

MySQL: How do I get to a column of another table via a mapping table

I am trying to create a database for assignments where there is a table for the tasks, a table for the persons and a table for the assignment of a person to a task.
Now I have tried to access the task table with a select statement and at the same time get all assigned persons but nothing worked. (because a task is also assigned to other tables)
Is there a way or do I have to use several statements for this?
This is how i created my Tables:
CREATE TABLE Locations (ID INT AUTO_INCREMENT, LocationID VARCHAR(255),
PRIMARY KEY (ID));
CREATE TABLE Persons (ID INT AUTO_INCREMENT, FirstName VARCHAR(255), LastName
VARCHAR(255), PRIMARY KEY (ID));
CREATE TABLE Tasks (ID INT AUTO_INCREMENT , TaskName VARCHAR(255), LocationID
INT, PRIMARY KEY (ID),
FOREIGN KEY (LocationID) REFERENCES Locations(ID));
CREATE TABLE Assinment (TaskID INT, PersonID INT,
PRIMARY KEY (TaskID, PersonID), FOREIGN KEY (TaskID)
REFERENCES Tasks(ID), FOREIGN KEY (PersonID)
REFERENCES Persons(ID));
And this is the UML.
I do not want my joins on the Assinment table like
SELECT (FirstName, LastName, TaskName) FROM ((Assinment INNER JOIN Tasks ON
Assinment.TaskID = Tasks.ID) INNER JOIN Persons ON Assinment.PersonID =
Persons.ID)
because the tasks table has more joins (e.g. locations and priorities) so i want my query start with
SELECT (ID, TaskName, FirstName, LastName, LocationName) FROM Tasks [...]
so i can get all data by id of the task
The Output then should give me this table.
Thanks for help :)
EDIT
Ouput added and desired input is now more specified
You can try subqueries :
SELECT column-names
FROM table-name1
WHERE value IN (SELECT column-name
FROM table-name2
WHERE condition)

Using of unique column name for each primary and foreign keys in mysql table to avoid ambiguous condition

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.

How to pass references from parent table to child table in mysql database

I am new to database.
my question is that i have created a table signUp whose columns are
id, first name, last name, email and country.
and i want to create a table named accout_recharge whose columns are (email,balance)
and whenever i insert a record into signup table the newly added email in the signup table also appear in account_recharge table using references or foreign key or whatever is required but without duplication.
you can try this
CREATE TABLE signup (
id INT NOT NULL,
firstName varchar(50),
lastName varchar(50),
countryName varchar(50),
emailName varchar(50),
PRIMARY KEY (id),
index email_ind(emailName) -- updated here
) ENGINE=INNODB;
CREATE TABLE accout_recharge(
id INT,
balance DECIMAL,
email varchar(50),
FOREIGN KEY (email ) REFERENCES signup (emailName)
ON DELETE CASCADE
) ENGINE=INNODB;
MySql Foreign Key here you find more detail about foreign key reference
Update: I forget to tell you that foreign key reference always some kind of indexed column. so you need to turn you email column in an index. that why you are getting error: 150

SQL Statement to write table?

working on a social networking project. just have to put together the sql statement to create the tables and need a little help with how this would be done, and how the relationships would work between the tables.
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
Password char(15),
primary key (id);
create table Instrests(
id INT,
create table friendships(
this can be done with just three tables
so far i have this done.
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
User_password char(15),
primary key (id)
foriegn key (intrest_id) references intrest(id)
);
create table Intrests(
id INT,
description char(30),
Primary key (id),
foreign key (users_id) references users(id)
);
create table User_intrest(
foreign key (user_id) references user(id),
foreign key (intrest_id) references intrest(id)
);
create friendships(
User_1_id INT,
User_2_id INT,
status Char(20),
foreign key (user_id) references user(id)
);
It looks like you're asking how to create the Interests and Friendships tables? And how they relate?
First, you'll need to spell Interests the same in the drop and create statement. You're right that Interests will link back to the Users by the ID. You'll probably want both an Interests Table, with an InterestID and description, and a linking table, with both the UserID and InterestID. Otherwise, you'll have lots of duplicate interests listed, one for each user.
The friendships table may be just a linking table, linking two userIDs together.
Try to imagine the data you need, and create the tables based on that:
User - 1, name - Joe, other info...
User - 2, name - Kris, other info..
User - 3, name - Lee, other info...
Interest - 1, name - reading
Interest - 2, name - parasailing
Interest - 3, name - skimboarding
UserInterest - User 1, Interest 2
UserInterest - User 1, Interest 3
UserInterest - User 2, Interest 2
Friendship - User 1, User 2
That tells you that Joe and Kris are friends and they both like parasailing, although Joe also likes skimboarding.
This doesn't tell you how to create the tables, but perhaps it will point you in the right direction. If this is a homework assignment, and it looks like it, you still want to do the work yourself.
You will need a an intermediate table between Users and Interests if you plan on having a many to many relationship between the two tables.
Also for Friendship, I would recomend a intermediate table between Friendship and Users as well, with that table having a link to a "Friendship Type" table to identify the friendship/relationship.
And if ThursdayGeek is correct and this is a homework assignment then I will stop here with my suggestions because there is more to the intermediate tables that you need to learn about before you implement them.
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
User_password char(15),
primary key (id)
foriegn key (intrest_id) references intrest(id)
);
create table Intrests(
id INT,
description char(30),
Primary key (id),
foreign key (users_id) references users(id)
);
create table User_intrest(
foreign key (user_id) references user(id),
foreign key (intrest_id) references intrest(id)
);
create friendships(
User_1_id INT,
User_2_id INT,
status Char(20),
foreign key (user_id) references user(id)
);
sorry not really good at this, anyways, this is what I have done for the sql statements so far.