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

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.

Related

Creating Association between two entries in SQL table

I have a piece of work to do setting up a database for a small enterprise.
Currently I have 5 tables set up:
Customers
Accounts
Associations
Security(Collateral)
References (Reference Codes relating to a Job type)
One of the tasks I have is to create an association table that will link to the Customers table and show the association between 2 customers.
Columns for Association table:
AssociationID
Customer1
AssociationType
Customer2
The output should be "Customer1 is AssocationType of Customer2" eg "Dave is Accountant for Jim"
How do I set it up so that Customer1 & Customer2 are from the Customer's table? I think it might be with Foreign Keys but I am unsure.
You can set up foreign keys:
alter table associations add constraint fk_associations_customer1
foreign key (customer1_id) references customers (customer_id);
alter table associations add constraint fk_associations_customer2
foreign key (customer2_id) references customers (customer_id);
Foreign keys should be made to the primary key, so you need to define customers so:
create table customers (
customer_id int primary key, -- perhaps identity, serial or autoincrement depending on your database
. . .
);
You'll note the naming conventions:
Tables are in the plural (the contain multiple examples of something).
The primary key is the singular followed by _id.
The foreign key is either the same name as, or very similar to, the primary key of the referenced table.

Adding multiple foreign keys in column

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.

Why can't I add this foreign key?

I'll post only the main part. I have two tables, each one has to have the PK of the other as a FK.
CREATE TABLE apartment
(
cod_apartment INT NOT NULL PRIMARY KEY,
cod_offer INT NOT NULL
);
CREATE TABLE offer
(
cod_offer INT NOT NULL PRIMARY KEY,
cod_apartment INT NOT NULL
);
First I inserted the values on both tables and it was working, I could even search using "select * from...". But then I tried to add the foreign key:
This worked.
ALTER TABLE offer
ADD FOREIGN KEY (cod_apartment ) REFERENCES apartment;
And this not.
ALTER TABLE apartment
ADD FOREIGN KEY (cod_offer) REFERENCES offer;
This is the error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__apartment__cod_offer__6383C8BA". The conflict occurred in database "kleber_apartment", table "dbo.offer", column 'cod_offer'.
The problem is, every time I try to execute, the FK name changes. And this FK actually doesn't exist. I already dropped both tables and tried to insert the values again, but the same happens.
What could be?
That means you're trying to add a foreign key when existing data doesn't obey that constraint. So you have a record in your apartment table where the cod_offer column does not match any value in the cod_apartment table.
Adding a foreign key not only constrains future data, but it requires that any existing data must also follow the rule.
And regarding the 6383C8BA, whenever you add a constraint without giving it a name, SQL Server picks one for you. Personally, I'd recommend something like:
alter table dbo.apartment
add constraint FK_apartment__cod_offer
foreign key (cod_offer) references dbo.offer (cod_offer);
This lets you define names the way you want, and is a little more clear about what you're actually building.

Adding Constraint with multiple foreign keys

I have a SQL database opened with visual studio, and I need to add some constraints to a table already created. I need a foreign key, which already has a foreign key from a third table. To explain better ,
Table ANIMALI needs a foreign key from table GABBIA, which has already a foreign key from table STANZA. This was the code I came up with:
ALTER TABLE ANIMALE ADD CONSTRAINT REF_ANIMA_GABBI_FK FOREIGN KEY (n_stanza, n_gabbia) REFERENCES GABBIA(n_stanza, n_gabbia);
This gives me an error, n_stanza is a column id not valid. I think it's about the fact that the ID for the class GABBIA is taken from joining n_gabbia and n_stanza, the latter being a key in class STANZA.
Can anyone help me out?
In order for your ALTER TABLE statement to work as written, both tables (not classes) "ANIMALE" and "GABBIA" must include the columns "n_stanza" and "n_gabbia".
In addition, in the table "GABBIA", there must be either a primary key constraint or a unique constraint on the pair of columns "n_stanza" and "n_gabbia". That is, you need something like either primary key (n_stanza, n_gabbia) or unique (n_stanza, n_gabbia) in the table "GABBIA".

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)
);