Using foreign keys in a SQL table - sql

I'm trying to reference a foreign key in a table to reference the primary key of another in order to get an attribute from that table. I think I worded that right.
It looks more obvious what I"m trying to do when you look at the code.
SELECT PATIENT_T.FIRST_NAME, PATIENT_T.LAST_NAME, TREATMENT_TYPE
FROM TREAMENT;
Where Patient_T is another table, where the primary key is PATIENT_ID.
Treatment is the table I'm searching from, where Treatment_ID is the primary key of that, and treatment type is another attribute.
Treatment has PATIENT_ID as a foreign key, so I thought that meant I could reference the first and last name by some sort of reference.
Did I type it wrong or how exactly do i do this?

Try like below
SELECT PATIENT_T.FIRST_NAME, PATIENT_T.LAST_NAME, TREATMENT_TYPE FROM TREAMENT
LEFT JOIN Patient_T.PATIENT_ID = TREAMENT.PATIENT_ID

Related

What does it mean when there is no "Id" at the end of a column name which appears to be a foreign key?

This is the databases ERD my final project for school is on (at the bottom), I am required to make a database using this information. I understand how to add the tables that are setup like 'trainer' and even how to add self-joining tables to my database, but something we have NOT learned is what it means or what to do when there is no Id at the end? Like 'evolvesfrom' and 'pokemonfightexppoint'.
Do you not have to add an Id at the end? From what my teacher taught us, I assumed you did. From what I see in this ERD is how evolvesfrom is self-joining itself to pokemonId. I know how to complete this only when there is an Id at the end of evolvesfrom.
For something like trainerId, it is super easy to understand how to add the constraints and everything like so:
CREATE TABLE trainer (
trainerId INT IDENTITY(1, 1),
trainerName VARCHAR(50) NOT NULL,
CONSTRAINT pk_trainer_trainerId PRIMARY KEY (trainerId)
);
I just don't understand how to do this when there is no Id added. For the pokemonFight table, it is noted that "It is assumed that a
Pokémon can play any battles at any battle locations. In other words, the battle experience points are functionally dependent on Pokémon, battle, and battle location", if that makes a difference.
If possible, could anyone show me an example on how to add a table, with constraints on either the pokemon or the pokemonFight table? (obviously you don't have to include the data types or anything).
Thank you in advance.
I am using SQL Server.
There is no required naming convention for columns in SQL Server that differentiates between a data column, a primary key column or a foreign key column.
The only constraints on column names are that they follow the rules for SQL Server identifier naming. However in a particular work environment you might well use a naming convention which does include ID at the end of the column name in order to clearly make the intention of the column obvious.
To create a self-referencing foreign key you just do the same as normal which can be as part of the create table or an alter table.
CREATE TABLE pokemon (
pokemonId INT IDENTITY(1, 1),
...
CONSTRAINT fk_pokemon_evolvesFrom FOREIGN KEY (evolvesFrom) REFERENCES pokemon (pokemonId)
);
-- OR
ALTER TABLE pokemon
ADD CONSTRAINT fk_pokemon_evolvesFrom FOREIGN KEY (evolvesFrom)
REFERENCES pokemon (pokemonId)

A table that does not have a primary key and has only one foreign key, can the foreign key be duplicated?

Assuming that the EMP_SALARY_INFO table does not have any other relations apart from the EMPLOYEE table.
My question is there is no primary key for the EMP_SALARY_INFO table. There is only one foreign key. When I create entity instances for the EMP_SALARY_INFO table, my foreign key i.e., EMP_ID repeats. Is this valid or does it violate any relational database rule? If this repetition is a violation, would I have to create a unique id (primary key) for the EMP_SALARY_INFO table?
That is perfectly OK. I would call out that in your example there is a possibility of having duplicate date ranges for the same employee. For example, if a mistake is made during data entry you may have two different pay rates for the same date range. Now, this may be a valid scenario in your case, however if it’s not then consider creating a unique constraint on Emp_id, from_date and till_date.
Foreign key of a particular table is a primary key of the table its referring to. Hence, in your case above as long as you have data in your empid of employee and same data if referred from emp_salary_info wont cause any sort of problem even if it repeats in the emp_salary_info table as its not repeating in the table its referring to i.e. Employee

The columns in 'table_XXX' do not match an existing primiary key or UNIQUE constraint

I have 2 simple tables designed as shown below:
Users:
Categories:
Now I would like to set the username as foreign key on categories table so this is what I have done but getting the error as shown below:
Am I doing the right way? Or can anyone suggest me the right way of doing this ?
*NOTE: I have tried to remove the primary key from the 2 tables and added them back and tried but showing me the same error.
You are not doing it the right way - hence the error. Put userid in your categories table and join to users if you need the name.
In fact, if that field represents the person who created the category, it should be named something like CreatedByUserId. It should still reference users.userid.
Impose a unique constraint on the username column in Users table. Then you can create the FK as shown. That said, having username in both tables is not a very good design. You should remove username and include userid in Categories table and make that a FK instead.
A foreign key constraint does not have to be linked only to a primary
key constraint in another table; it can also be defined to reference
the columns of a UNIQUE constraint in another table.
in Create Foreign Key Relationships
You have to set a constraint in table Users in order to username to be unique.
Try to change in the table Categories the name of the foreign key field.
It seems that it "autowire" fields using their name. What i mean is : change Categories.username to Categories.userid.
Your column username in the table users must have a unique constraint if you want to set up the foreign key relationship in your screenshot.

How to reference a composite primary key into a single field?

I got this composite primary key in Table 1:
Table 1: Applicant
CreationDate PK
FamilyId PK
MemberId PK
I need to create a foreign key in Table 2 to reference this composite key. But i do not want to create three fields in Table 2 but to concatenate them in a single field.
Table 2: Sales
SalesId int,
ApplicantId -- This should be "CreationDate-FamilyId-MemberId"
What are the possible ways to achieve this ?
Note: I know i can create another field in Table 1 with the three columns concatenation but then i will have redundant info
What you're asking for is tantamount to saying "I want to treat three pieces of information as one piece of information without explicitly making it one piece of information". Which is to say that it's not possible.
That said, there are ways to make happen what you want to happen
Create a surrogate key (i.e. identity column) and use that as the FK reference
Create a computed column that is the concatenation of the three columns and use that as the FK reference
All else being equal (ease of implementation, politics, etc), I'd prefer the first. What you have is really a natural key and doesn't make a good PK if it's going to be referenced externally. Which isn't to say that you can't enforce uniqueness with a unique key; you can and should.

SQL Server 2008: The columns in table do not match an existing primary key or unique constraint

I need to make some changes to a SQL Server 2008 database.
This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne.
However when I tried to do this (through SQL Server Management Studio) I got the following error:
The columns in table 'tblOne' do not
match an existing primary key or
UNIQUE constraint
I'm not really sure what this means, and I was wondering if there was any way around it?
It means that the primary key in tblOne hasn't been properly declared - you need to go to tblOne and add the PRIMARY KEY constraint back onto it.
If you're sure that tblOne does have a PRIMARY KEY constraint, then maybe there are multiple tblOne tables in your DB, belonging to different schemas, and your references clause in your FK constraint is picking the wrong one.
If there's a composite key (which your comment would indicate), then you have to include both columns in your foreign key reference also. Note that a table can't have multiple primary keys - but if it has a composite key, you'll see a key symbol next to each column that is part of the primary key.
If you have a composite key the order is important when creating a FK, and sometimes the order is not how it is displayed.
What I do is go to the Keys section of the table1 and select script primary key as create to clipboard and then create FK using the order as shown in script
I've had this situation that led me to this topic. Same error but another cause. Maybe it will help someone.
Table1
ColA (PK)
ColB (PK)
ColC
Table2
ID (PK)
ColA
COLB
When trying to create foreign key in Table2 I've choose values from combobox in reverse order
Table1.ColB = Table2.ColB
Table1.ColA = Table2.ColA
This was throwing me an error like in topic name. Creating FK keeping order of columns in Primary key table as they are, made error disappear.
Stupid, but.. :)
If you still get that error after you have followed all advice from the above answers and everything looks right.
One way to fix it is by Removing your Primary keys for both tables, Save, Refresh, and add them again.
Then try to add your relationship again.
This Error happened with me When I tried to add foreign key constraint starting from PrimaryKey Table
Simpy go to other table and and create this foreign key constraint from there (foreign key Table)
This issue caught me out, I was adding the relationship on the wrong table. So if you're trying to add a relationship in table A to table B, try adding the relationship in table B to table A.
That looks like you are trying to create a foreign key in tblTwo that does not match (or participate) with any primary key or unique index in tblOne.
Check this link on MSDN regarding it. Here you have another link with a practical case.
EDIT:
Answwering to your comment, I understand you mean there are 2 fields in the primary key (which makes it a composite). In SQL it is not possible to have 2 primary keys on the same table.
IMHO, a foreign key field should always refer to a single register in the referenced table (i.e. the whole primary key in your case). That means you need to put both fields of the tblOne primary key in tblTwo before creating the foreign key.
Anyway, I have investigated a bit over the Internet and it seems SQL Server 2008 (as some prior versions and other RDBMS) gives you the possibility to reference only part of the primary key as long as this part is a candidate key (Not Null and Unique) and you create an unique constraint on it.
I am not sure you can use that in your case, but check this link for more information on it.
I have found that the column names must match.
Example:
So if tblOne has id called categoryId a reference in tblTwo must also be called categoryId.
_tblname, primary key name, foreign key_
tblOne, "categoryId", none
tblTwo, "exampleId", "categoryId"
I noticed this when trying to create foreign key between 2 tables that both had the column name "id" as primary key.
If nothing helps, then this could be the reason:
Considering this case:
Table A:
Column 1 (Primary Key)
Column 2 (Primary Key)
Column 3
Column 4
Table B:
Column a (Primary Key)
Column b
Column c
when you are defining a dependency B to A, then you are forced to respect the order in which the primaries are defined.
That's mean your dependency should look like this:
Table A Table B
Column 1 Column b
Column 2 Column c
AND NOT:
Table A Table B
Column 2 Column c
Column 1 Column b
then this will lead to the error you are encountering.
I've found another way to get this error. This can also happen if you are trying to make a recursive foreign key (a foreign key to the primary key in the same table) in design view in SQL Management Studio. If you haven't yet saved the table with the primary key it will return this message. Simply save the table then it will allow you to create the foreign key.
If you have data in your tables this could be the issue.
In my case I had some data in the Account table that I loaded at 3 pm, and some data in Contact table that I loaded at 3:10 pm, so Contact table had some values that weren't in my Account table yet.
I ended up deleting these values from the contact table and then managed to add a key without any problems.
Kindly also see that there are no existing data inside the table where the primary key is defined while setting the foreign key with another table column.
this was the cause of the error in my case.
I had to take backup empty the table set the relationship and then upload the data back.
sharing my experience
Was using ms sql smss