Adding multiple foreign keys in column - sql

Is there a way to store multiple values in a column that has a foreign key constraint?
Let's say I have a states table and a project table. Project table has a foreign key constraint with states table. Now we are implementing the same project in three different states. How can I select multiple states?
Sample
Create table states (
Stateid int identity primary key,
State varchar(100)
);
Projects Table
Create table projects (
ProjId int primary key identity,
ProjTitle varchar (100),
Budget decimal,
);
How can I insert multiple values in projects states table?
Based on TPHE answer lets me create another table called projectstates
Create table projectstates(
projStatid int identity primary key,
stateid int,
ProjId int
constraint fk_ProjId foreign key (ProjId) references Projects(ProjId),
constraint fk_stateid foreign key (stateid) references states(StateId)
);
Now how can i insert data in ProjectStates while adding project to the project table?

The best way I've found to do this is to create the second table with no foreign key constraint at first. Then you can populate both tables with the data, then introduce the constraint afterwards - assuming the data in the tables complies with the constraint.
Also, if a many to many relationship exists, add in a mapping table to allow this.

It would break some basic rules of database design to add multiple values. You should create a new table that has a one to many relationship with the states table (each state can have multiple values in the new table) and contains a column for the associated project IDs (also with a one-to-many relationship). Then you would join from the states table to the new table and then to the projects table or vice versa. More info on how and why to design databases in this way.

Related

How to create associative table where one of the fields is not primary key?

I am structuring a postgres database.
I have two tables, products (coke) and optional (with ice, lemon ...), that is, a relationship many to many.
An associative table is usually built using the primary keys of the tables, correct? However, in my case, there is a specific feature ... due to some imports from other databases...I have two ids fields (id and "externalId"), one primary key and one common ... one is the local id of my bank and the other represents the id that the item has in the bank from which it was imported.
I need an associative table between "externalId" and a primary key from another table.
ExternalId is not a primary key...
ALTER TABLE public.opcional_produto
Add
CONSTRAINT idproduto_fkey FOREIGN KEY (prod_id) REFERENCES public.produto (prod_idExt)
ERROR: there is no unique constraint matching given keys for
referenced table "produto" SQL state: 42830
How can I do?
If externalid is unique, you should create a unique constraint:
ALTER TABLE produto ADD UNIQUE (externalid);
Ideally it should also be not nullable:
ALTER TABLE produto ALTER externalid SET NOT NULL;
Now it can be used as target of a foreign key.

How to setup tables with varying number of Foreign Key of specific type

Say I have three tables.
MenuItem(MenuItemID{PK}, MenuItemName, MenuItemIngredient)
Ingredient(IngredientID{PK}, IngredientName, SupplierID)
Supplier(SupplierID{PK}, SupplierName)
Each MenuItem in the MenuItem table can have multiple ingredients.
Each Ingredient in the Ingredient table can have multiple suppliers.
My current way of doing this is to have two extra tables.
MenuIngredientLink(MenuItemID{PK}, IngredientID{FK})
IngredientSupplierLink(IngredientID{PK}, SupplierID{FK})
Then remove the last column on MenuItem and Ingredient tables.
This doesn't really seem like a good way to do it though.
Any alternatives?
Fairly new to SQL so any help would be appreciated.
Using Microsoft SQL Server 2014.
Since everything follows a strict one-to-many relationship,your original approach to the problem is correct.So no need to introduce two mapping tables.
However, a problem arises in a scenario like this. An ingredient is supplied by many suppliers as well as a supplier provides multiple ingredients, creating a many-to-many relationship.Then your approach to a mapping table is the preferred solution.
I have included an external source for your reference. Hope this helps.
Managing Database Relationships
We can make tables with foreign keys as you've specified. If you start with the Supplier table, you should insert all values required, and it has no foreign key so you have no restrictions. Next, you insert values into the Ingredients table, since it requires a foreign key to Suppliers. Lastly, you insert values into the MenuItem table, since it has a foreign key to Ingredient. You can create the tables first, then add the foreign keys later as I've written below.
--Suppliers does not have any foreign keys
CREATE TABLE Supplier (SupplierID int PRIMARY KEY, SupplierName varchar(100))
--Ingredients has a foreign key to Supplier(SupplierID)
CREATE TABLE Ingredient (IngredientID int PRIMARY KEY
, IngredientName varchar(100)
, SupplierID int)
ALTER TABLE Ingredient ADD FOREIGN KEY (SupplierID) REFERENCES Supplier(SupplierID)
--MenuItem has a foreign key to Ingredient(IngredientID)
CREATE TABLE MenuItem (MenuItemID int PRIMARY KEY
, MenuItemName varchar(100)
, MenuItemIngredientID int)
ALTER TABLE MenuItem ADD FOREIGN KEY (MenuItemIngredientID) REFERENCES Ingredient(IngredientID)

Creating relation between tables in Movie Database

I have created a movie database that contain following tables :
1.Film
2.People
3.Genres
4.Role
5.Users
Here is my sql
create table Film ( id INT(30),title varchar(30),images varchar(30)
primary key (id));
create table people(id INT(30),Fname varchar(30),Lname varchar(30),
primary key (id));
create table Role(id INT(30), name varchar(30),
primary key(id));
i want create relation between Film,People and Role table.SO my Question is do i need to create a table to make relation between those table and is it necessary to use auto_increment for id column?
You'd want to create some tables like:
FilmRole( FilmId INT, RoleId INT) these 2 columns would make your PK and they are also FK's to their
FilmPeople (FilmId INT, PeopleId INT) respective source tables.
FilmUsers( FilmId INT, UserId INT)
You could add a single IDENTITY (for SQL Server for example) column to each table if you wanted but in this particular case a 2 column PK is adequate as these tables simply point to other records.
You need to alter your table and add in a foreign key (Primary key in one table and attribute in another). Examples how to do it here! http://www.w3schools.com/sql/sql_foreignkey.asp
do i need to create a table to make relation between those table ?
YES ! to enforce Referential integrity read this
is it necessary to use auto_increment for id column?
Depends but it is most prefered way of creating a PK on a table

How to create linking/joining table in Oracle database

I'm creating a mock up database for the first time. I have created the Relational Model which consists of a many to many relationship. In the Relational Model it has a separate linking/joining table. When creating the database do I need to create this linking table as a separate table also? Or can I just put each foreign keys in the many to many tables?
If I need a separate table how do I link these tables together via syntax?
Thanks
We can only build foreign keys in a one-to-many fashion. So you need this intersection table. It is the sort of additional construct we introduce when transforming a logical data model into a physical one.
The intersection table often has just two columns, the referencing keys of the two tables you want to link in M:N fashion (there may also be some metadata columns to hold properties of the link). It usually has a compound primary key on the two columns, to avoid redundancy. It has a foreign key on each of the referenced tables, which must have defined primary keys on the referenced columns.
The syntax is pretty obvious; this sample builds two master tables and an intersection defining just the keys.
create table m1 (
id number not null
, constraint m1_pk primary key (id) );
create table m2 (
id number not null
, constraint m2_pk primary key (id) );
create table intersection_t (
m1_id number not null
, m2_id number not null
, constraint int_pk primary key (m1_id, m2_id)
, constraint int_m1_fk foreign key (m1_id)
references m1 (id)
, constraint int_m2_fk foreign key (m2_id)
references m2 (id)
);

How can I share the same primary key across two tables?

I'm reading a book on EF4 and I came across this problem situation:
So I was wondering how to create this database so I can follow along with the example in the book.
How would I create these tables, using simple TSQL commands? Forget about creating the database, imagine it already exists.
You've been given the code. I want to share some information on why you might want to have two tables in a relationship like that.
First when two tables have the same Primary Key and have a foreign key relationship, that means they have a one-to-one relationship. So why not just put them in the same table? There are several reasons why you might split some information out to a separate table.
First the information is conceptually separate. If the information contained in the second table relates to a separate specific concern, it makes it easier to work with it the data is in a separate table. For instance in your example they have separated out images even though they only intend to have one record per SKU. This gives you the flexibility to easily change the table later to a one-many relationship if you decide you need multiple images. It also means that when you query just for images you don't have to actually hit the other (perhaps significantly larger) table.
Which bring us to reason two to do this. You currently have a one-one relationship but you know that a future release is already scheduled to turn that to a one-many relationship. In this case it's easier to design into a separate table, so that you won't break all your code when you move to that structure. If I were planning to do this I would go ahead and create a surrogate key as the PK and create a unique index on the FK. This way when you go to the one-many relationship, all you have to do is drop the unique index and replace it with a regular index.
Another reason to separate out a one-one relationship is if the table is getting too wide. Sometimes you just have too much information about an entity to easily fit it in the maximum size a record can have. In this case, you tend to take the least used fields (or those that conceptually fit together) and move them to a separate table.
Another reason to separate them out is that although you have a one-one relationship, you may not need a record of what is in the child table for most records in the parent table. So rather than having a lot of null values in the parent table, you split it out.
The code shown by the others assumes a character-based PK. If you want a relationship of this sort when you have an auto-generating Int or GUID, you need to do the autogeneration only on the parent table. Then you store that value in the child table rather than generating a new one on that table.
When it says the tables share the same primary key, it just means that there is a field with the same name in each table, both set as Primary Keys.
Create Tables
CREATE TABLE [Product (Chapter 2)](
SKU varchar(50) NOT NULL,
Description varchar(50) NULL,
Price numeric(18, 2) NULL,
CONSTRAINT [PK_Product (Chapter 2)] PRIMARY KEY CLUSTERED
(
SKU ASC
)
)
CREATE TABLE [ProductWebInfo (Chapter 2)](
SKU varchar(50) NOT NULL,
ImageURL varchar(50) NULL,
CONSTRAINT [PK_ProductWebInfo (Chapter 2)] PRIMARY KEY CLUSTERED
(
SKU ASC
)
)
Create Relationships
ALTER TABLE [ProductWebInfo (Chapter 2)]
ADD CONSTRAINT fk_SKU
FOREIGN KEY(SKU)
REFERENCES [Product (Chapter 2)] (SKU)
It may look a bit simpler if the table names are just single words (and not key words, either), for example, if the table names were just Product and ProductWebInfo, without the (Chapter 2) appended:
ALTER TABLE ProductWebInfo
ADD CONSTRAINT fk_SKU
FOREIGN KEY(SKU)
REFERENCES Product(SKU)
This simply an example that I threw together using the table designer in SSMS, but should give you an idea (note the foreign key constraint at the end):
CREATE TABLE dbo.Product
(
SKU int NOT NULL IDENTITY (1, 1),
Description varchar(50) NOT NULL,
Price numeric(18, 2) NOT NULL
) ON [PRIMARY]
ALTER TABLE dbo.Product ADD CONSTRAINT
PK_Product PRIMARY KEY CLUSTERED
(
SKU
)
CREATE TABLE dbo.ProductWebInfo
(
SKU int NOT NULL,
ImageUrl varchar(50) NULL
) ON [PRIMARY]
ALTER TABLE dbo.ProductWebInfo ADD CONSTRAINT
FK_ProductWebInfo_Product FOREIGN KEY
(
SKU
) REFERENCES dbo.Product
(
SKU
) ON UPDATE NO ACTION
ON DELETE NO ACTION
See how to create a foreign key constraint. http://msdn.microsoft.com/en-us/library/ms175464.aspx This also has links to creating tables. You'll need to create the database as well.
To answer your question:
ALTER TABLE ProductWebInfo
ADD CONSTRAINT fk_SKU
FOREIGN KEY (SKU)
REFERENCES Product(SKU)