Relationship between composite keyed table & non primary key table - sql

I have two tables named ORDER_HEAD and ORDER_DETAIL, following is their structure.
ORDER_HEAD:
ORD_ID (PK)
ORD_TYPE (PK)
ORD_DATE
ORD_NET_TOTAL
ORDER_DETAIL:
ODD_ID
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
I want to form a relationship between the ORD_ID in ORDER_HEAD & ODD_ID in ORDER_DETAIL table. But SQL Server shows an error message:
primary key or unique constraint must be defined for table before it can participate in a relationship
Why am I getting this error ? Is there a way to perform a join between these two columns or is there a problem in my db design ?

If you want to create a relationship from Composite primary key then any reference should also include all the column's in Composite primary key
Schema of ORDER_DETAIL should be
ORDER_DETAIL
============
ODD_ID (Fk)
ORD_TYPE(Fk) -- you need to add this column
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
Create Foreign key like this.
ALTER TABLE ORDER_DETAIL
ADD CONSTRAINT FK_ORDER_DETAIL
FOREIGN KEY(ODD_ID, ORD_TYPE) REFERENCES ORDER_HEAD(ODD_ID, ORD_TYPE)

UPDATE
After rethinking the problem I think you should achieve your goal by adding reference column ODD_TYPE (like user #NoDisplayName stated) and creating composite PK for your table ORDER_DETAIL consisting of 3 columns (ODD_ID, ODD_TYPE, ODD_LINE_NO), then it would be:
ORDER_DETAIL
============
ODD_ID (PK)
ODD_TYPE (PK)
ODD_LINE_NO (PK)
ODD_PRODUCT_ID
ODD_QTY
in SQL it could be:
ALTER TABLE ORDER_DETAIL ADD CONSTRAINT PK_Order_Detail PRIMARY KEY NONCLUSTERED (ODD_ID, ODD_TYPE, ODD_LINE_NO)
Then, in ORDER_DETAIL table for specific pair (ODD_ID, ODD_TYPE) you would have records being its order lines.
I think that after removing the previous PK, adding the column and setting the above key (even in visual editor) you shouldn't have problems when creating FK between the two tables and mapping the proper columns together.

Related

SQL Insert into table with 2 non-unique primary keys

I have a table that I need to insert data into.
The table Sales has 4 columns
CustomerValueType_id (int)
Customer_id (int)
Value (NVARCHAR)
Customer_name (NVARCHAR)
The CustomerValueType_id, Customer_id are foreign keys that are not-unique, CustomerValueType_id matches to a value type, while Customer_id matches to the Customer_name.
I need to add additional customer data into the Valuecolumn but how do I ensure that the data matches to the correct CustomerValueType_id and Customer_id and each customer name has to be repeated in the Customer_name
Sales Table
You are trying to do denormalization.
Ideally, in the normalized design, you will just store, parent_ids in
the child table. If you want to see parent_name fields, you have to
get them based on JOIN conditions.
But, here as you are storing both id, name in the child table, I would suggest you to create composite Foreign key in the child table, so that the combination is always present. Also, make this combination as composite primary key in the parent table.
-- Parent Table PRIMARY KEY
ALTER TABLE dbo.CustomerValueType
ADD CONSTRAINT PK_CustomerValueType
PRIMARY KEY CLUSTERED (CustomerValueType_id, Value);
GO
--Child Table FOREIGN KEY
ALTER TABLE dbo.Sales
ADD CONSTRAINT FK_Sales_CustomerValueType
FOREIGN KEY (CustomerValueType_id,Value)
REFERENCES dbo.CustomerValueType(CustomerValueType_id,Value);
GO

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.

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.

Relation from one table to another with two columns in the primary key in SQL Server

I am trying to make a relation from a table to another like the following :
Books
IdBook (primary)
SerialNumber (primary)
NameBook
The other table is :
Qtt
IdQtt (primary)
IdBook
Qtt
How can I make a relation only between Qtt.IdBook and Books.IdBook ?
You meant to create a FOREIGN KEY relationship between the tables on that column like
CONSTRAINT FK_idbook FOREIGN KEY (IdBook)
REFERENCES Books (IdBook)
ON DELETE CASCADE
ON UPDATE CASCADE
But that will not work since you have composite PK in your Books table on IdBook, SerialNumber and thus you need another key column in your Qtt table to refer to both PK column else it would be a PFD (partial functional dependency)
constraint FK_book FOREIGN KEY (IdBook,IdQtt) references Books (IdBook,SerialNumber)
Although it is technically possible to create a UNIQUE constraint on Books.IdBook and a FOREIGN KEY constraint on Qtt.Book referencing that column, this probably won't work with your data model because IdBook alone doesn't uniquely identify a Books row. You need a table like BookTitle keyed by IdBook, with a one-to-many relationship to Books and another one-to-many relationship from BookTitle to Qtt on IdBook.

SQL Foreign Key Redundancy

This is a question about foreign key redundancy
redundant foreign key? <- Similar Question
In General:
A Foreign Key from TABLE C references a Primary Key from Table B
A Foreign Key From Table C references a Primary Key from Table A
A Foreign Key from Table B references a Primary Key from Table A
Is the Foreign Key from C -> A necessary since C is connected through B to A?
Specific: 3 tables
Supplier Info Table A
Supplier ID - PK
Person Contact Info (for supplier) Table B
Part # - PK
Date Received - PK
Supplier ID - FK
Part Rprt Table C
Part # - PK & FK
Date - PK & FK
Supplier ID - FK
Thanks - Suggestions for reworking all the table are also welcome
The key would technically be redundant if you assume that the supplier for a person is always the supplier represented by the part. Remember, that things can change over time. Presumably, suppliers could merge, persons could change the supplier they are associated with, and the supplier associated with a part could change.
The data structure, however, does not look properly normalized. I would think that you would want a person table with information only about the person. I don't get the relationship between parts and persons.
So, I think you should rework your data structure. I would suggest that you start with the entities you have identified -- suppliers, persons, and parts. Then create association tables for them, if necessary. It is quite possible that each person should just have a SupplierId and each part should have a SupplierId and that models the relationships. If there is a relationship between parts and persons, then you might be able to satisfy that with just a PersonId field in parts.