Makine a composite foreign key that refers to two differnt tables - mysql

I'm making a schema for a hospital data base. I have 4 tables, candidate details, hospital details, position details and interview details. The interview table has a foreign key referring to the candidate table, one to the position's table and I also want it to have one referring to the hospital table but I noticed that it is possible then to have a tuple where the combination of the position id and the hospital id is not the same as the combination that occurs on the position tables (the position table has a foreign key referring to the hospital table) So in other words is makes it possible to enter the incorrect hospital id or position id in the interview table. So for instance on the interview table I could enter a tuple where the position id is 01 and the hospital id is 02 but if you go the positions table, the position id that is being refereed to could easily have a hospital id that is different (eg 03).
I was thinking that there might be away of creating a composite foreign key that refers to two different tables at the same time. If that's not the case, is the only way of resolving the issue, just removing the hospital id column from the interview table completely?
I've been using mySQL workbench so I don't have any of the SQL code on hand but if any extra information (eg ERR image) is required to answer this question I'll try my best to source it.

Short answer :
No, a foreign key constraint always references exactly one parent table.
However, If I understand your situation well, you have 4 tables
candidate details. id
hospital details. id
position details. id, hospital_id
interview details. candidate_id, hospital_id, position_id
The problem is the relation between postion and hospital is many to many
simple way EAV add another table call it hospital_postition, that has all the positions in all hospitals then link each hospital_postition to the condidate in the interview
candidate details. id
hospital details. id
position details. id
hospital_postition. id, hospital_id, position_id
interview details. candidate_id, hospital_position_id

Less is more!
You have this problem because the table isn't in 3rd normal form. hospital_id isn't dependent on the interview, it's dependent on the position, and position_id is not the KEY for this able.
Ask yourself, do I really want to record hospital_id in the interview table? All the information you probably need is already stored in the positions table. The only reason I can think of for wanting that column would be where you were conducting interviews in hospitals other than the one where the position is based. If that is the case then your schema is already correct but your question implies otherwise.
Drop the hospital_id column from the interview table and your problem will magically disappear.
On the subject of getting table definitions (SQL code) out of MySQL Workbench, try this:
Right-click the table name in the schema browser
Select "Send to SQL Editor"
Select "Create statement"

Related

Can A Foreign Key Be Used More than Once?

Apologies for the newbie question.
The primary key of a table, such as Holiday, would be something like Holiday_ID. Holiday reference a get-away ticket that you can buy to go on a type of holiday, based on the ticket you buy.
Suppose I used Holiday_ID in a composite entity with Customer_ID to identify an instance of Holiday associated with customer, for whatever purpose.
However, suppose I also want to keep track of other information related to this instace: how much has the customer paid for the ticket, how much has the customer yet to pay for the ticket
I have two options:
a) I can create another composite entity. However, I am not sure if I can do that because I am not sure if you can use a particualr foreign key more than once
b) I can create a composite/associate entity, however, I am not sure if you can create a composite entity with more than two foreign keys?
To answer the technical parts of your question, once you create a composite unique or primary key, ONLY ONE record in the table can have the same values in the set of fields defined in that key. SO, no, you cannot reuse the holidayId key WITH THE SAME customer. You can use it with another, different customer if you wish.
Second, there is no limit to the number of attributes that can be included in a Unique or primary key. If you need, and if it's appropriate and conforms to the rules of normalization, the key can include all the attributes of the table.
Third, to answer your question below, Any column, or set of columns in a table can be defined as a Foreign Key, as long as it is also the primary key or unique key of some table in the database. And there can be any number of FKs defined in a table, they can even overlap. (you can have HolidayId as a FK, and also have HolidayID and CustomerId as a composite FK) the only restriction is that the FK must reference a Primary or Unique Key of some table in the database.(It can also be the same table the FK is in as well, as when you add a supervisorId to an employee Table that is a FK to the EMployeeId of the same employee table)
This example illustrates one of the problems of using surrogate keys without also using a natural key. to wit, what, exactly is a "Holiday"? Is Christmas 2016 the same "Holiday" as Christmas 2015? Is Christmas in Aruba the same holiday as Christmas in Hawaii?
and then, about the composite table to identify associations of customer with Holiday, is it the same association if the customer goes to Aruba on Christmas the next year, or a different instance? What does the row in the table represent if the customer wants 5 tickets?
The first thing that should be done in database design is a logical design which defines, as clearly and unambiguously as possible, in business terms, the meanings of the entities for each table in the database.

phpmyadmin - How to set field values dependant on foreign key?

How do I setup fields to be dependent on what foreign key is input?
I have googled and searched stack overflow, using similar questions to that, but couldn't find anything that fitted what I was looking for. There are pictures and an example below to better describe what I am asking.
Here's my table (that I want fields to be dependant on there foreign keys):
jo_route is a foreign key for this table:
and jo_type is a foreign key for this table:
When I go to insert a record into the journeys table, and select the route id. How do I get the corresponding information from that foreign keys table to appear in the respective fields in this table.
For example, jo_type as 3 records (as shown in the picture). The foreign key jo_type is linked with this table. Say I select the ID for air (2) in the journeys table. How do I get the related fields (jo_seats_total) to be automatically chosen from the travel types table? So it should appear as 100.
Hopefully I have explained my problem well enough.
Thanks in advance for any help!
Sorry for the long post.
I hope this is something that you looking for...
SELECT t.tt_max_seat, t.tt_name, r.ro_origin, r.ro_destination,
j.jo_seats_total, j.jo_seats_take, j.jo_seats_available
FROM journey j
JOIN route r ON j.jo_route = r.ro_id
JOIN type t ON j.jo_type = t.tt_id
WHERE j.jo_type = 2

database table design and relationship complexity

Could someone suggest the best design for the following scenario?
I have a database in which there is a table called City. This table has the following fields:
City id (Primary key)
City Name
State Id (which is linked to the State table)
My problem is I have 10 cities with the same name in one state. What will be the best design so I can represent one city name per id?
It does not matter that they have the same City Name, as long as they have different City Ids.
Just make sure to set the CityId as primary key in the City table. Also, it would be useful to make it an identity autoincrement column, so that it is inserted automatically and will always be unique.
Same goes for StateId in the State table.
Also, if you use a visual management tool for the database, make sure to set the foreign key relationship between the two tables:
FK_State.StateId_City.StateId.

Can a foreign key act as a primary key?

I'm currently designing a database structure for our team's project. I have this very question in mind currently: Is it possible to have a foreign key act as a primary key on another table?
Here are some of the tables of our system's database design:
user_accounts
students
guidance_counselors
What I wanted to happen is that the user_accounts table should contain the IDs (supposedly the login credential to the system) and passwords of both the student users and guidance counselor users. In short, the primary keys of both the students and guidance_counselors table are also the foreign key from the user_accounts table. But I am not sure if it is allowed.
Another question is: a student_rec table also exists, which requires a student_number (which is the user_id in the user_accounts table) and a guidance_counsellor_id (which is also the user_id in the user_accounts) for each of its record. If both the IDs of a student and guidance counselor come from the user_accounts table, how would I design the student_rec table? And for future reference, how do I manually write it as an SQL code?
This has been bugging me and I can't find any specific or sure answer to my questions.
Of course. This is a common technique known as supertyping tables. As in your example, the idea is that one table contains a superset of entities and has common attributes describing a general entity, and other tables contain subsets of those entities with specific attributes. It's not unlike a simple class hierarchy in object-oriented design.
For your second question, one table can have two columns which are separately foreign keys to the same other table. When the database builds the query, it joins that other table twice. To illustrate in a SQL query (not sure about MySQL syntax, I haven't used it in a long time, so this is MS SQL syntax specifically), you would give that table two distinct aliases when selecting data. Something like this:
SELECT
student_accounts.name AS student_name,
counselor_accounts.name AS counselor_name
FROM
student_rec
INNER JOIN user_accounts AS student_accounts
ON student_rec.student_number = student_accounts.user_id
INNER JOIN user_accounts AS counselor_accounts
ON student_rec.guidance_counselor_id = counselor_accounts.user_id
This essentially takes the student_rec table and combines it with the user_accounts table twice, once on each column, and assigns two different aliases when combining them so as to tell them apart.
Yes, there should be no problem. Foreign keys and primary keys are orthogonal to each other, it's fine for a column or a set of columns to be both the primary key for that table (which requires them to be unique) and also to be associated with a primary key / unique constraint in another table.

mysql - It is ok to have n amount of columns?

I know it's possible to have n amount of columns, but is it proper mysql "coding standard"?
Here is what I'm doing:
I am a table student which includes all the students info including testScores:
student
-------
studId
name
age
gender
testId
Instead of putting each individual test answer within the student table, I made a separate table called testAnswers that will hold each students test results:
testAnswers
-----------
testId
ques1
ques2
.
.
.
quesN
Each entry in the testAnswers table corresponds to a specific student in the table student.
Of course, there will be an admin that will be able to add questions and remove questions as each year the test questions may change. So, if the admin were to remove an answer, than that means one of the columns would be removed.
Just to reiterate myself, I know this is possible to edit and remove columns in a table in mysql, but is good "coding standard"?
The answer is a simple and clear: No. That's just not how you should do it except for very few corner cases.
The usual way to approach this is to normalize your database. Normalization follows a standard procedure that (among other things) avoids having a table with columns names ques1, ques2, ques3 ....
This process will lead you to a database with three tables:
students - id, name, and other stuff that applies to one student each
questions - id and question text for each question
answers - this is a N:M relation between students: student_id, question_id, answer_value
Use two tables!
What you are describing is a one to many relationship as there can be one student to many test scores. You would need to have some id as a foreign key to the student_id and put this id in the testAnswers table. You can then set constraints, which tell the database how to handle removal of data.
As one commenter has mentioned, using one table would result in breaking 1nf or first normal form which basically says that you cannot have multiple values for a single column given a particular record - You can't have multiple test scores for the same user in a given table, instead break the data up into two tables.
...of course 2 tables, also could use 3, just remember to insert a studId column also in the testAnswers table (with REFERENCE to the student table) and an INNER JOIN testAnswers ON student.studId=testAnswers.studId at the SELECT query (to read the data).