How do I fix the following many to many relationship? - sql

I have to build a database as follows:
We have one table, called Organization. An Organization can have one or more products, which they sell. Then, I have a table called Products, which lists the Product title, cost, and amount sold.
How can I create a relationship where a organization.product can contain a reference to multiple rows from the products table?
I would imagine I would need to potentially create another table?
Thanks!

Assuming you have something like this for your Organization and Product tables.
Organization
Id (Primary Key)
Name
....
Product
Id (Primary Key)
Name
Cost
....
Then you would create a join table like this that would link your Organization to Products.
OrganizationProduct
Id (Primary Key)
OrganizationId (Foreign Key to Organization Table)
ProductId (Foreign Key to Product Table)

What you want to do here is have a table representing your products and in that table one of the fields should represent the Organisation which has the product, called something like org_id.
Then in your Organisation table you will have an id column to join with org_id from the product table.
Eg:
Products:
id int
org_id int
name varchar
colour varchar
.....
any other information about products
Organisations:
id int
name varchar
type varchar
...
other organisation details
Now when you want to list all the products for each company you do:
SELECT products.name, organisations.name
FROM products
JOIN organisations
ON products.org_id = organisations.id;
New information, products can belong ot multiple organisations. Now you need a table called organisationProducts to act as an intermediary between the two tables and create a many to many relationship:
Products:
id int
name varchar
Organisations:
id int
name varchar
OrgnisationProducts:
id int
Org_id
Prod_id
You join prod_id to products.id and org_id to organisations.id

What you want is called an associative table. Let's call it OrgProduct (I name all my tables in the singular; some shops name them plural, but be consistent).
OrgProduct will have at least the Organization key and Product key as columns, and the combo of the two keys will be the key to OrgProduct.
If there are properties of the relationship, such as a date when the right of an Organization to sell a Product expires, these would also be candidates for non-key columns in this table.

Related

How to design SQL Server table for a relation between same column values

In my database there is a table with my customers. Customers can be producers or traders of products to whom I deliver raw material.
Many producers have trading companies with different names which could be in my database listed as independently customers, further many of them have online-shops again with different names. So who belongs to whom is very difficult to find out and if I do, I have to "link" them together in my db.
My idea is to add a table with only 2 columns: CuID (customer ID from maintainable) and linked CuID (let's say I call this column ReID=relation ID also holding the CuID of a partner company.).
Whenever I detect one relation between them I add CuID in column CuID and the other companies CuID in column "ReID".
On an Access-form, I have a subform presenting all names of related customers (CuID:ReID =1:n).
But how can I present it vice versa, when I am on the record of a customer which is stored as ReID and present the CuID in column "CuID"?
Example:
Company A CuID=1 has ties to Company B CuID=3. In my table, I add 1 / 3
Company X CuID=7 has ties to Company B CuID=3. In my table, I add 7 /3
On form presenting Company A I find related Company B in a subform.
On form presenting Company X I find related Company B in a subform.
How can I present A and B as a relation to Company X on a form when X is presented??
I have not been able to find a proper solution for this requirement.
Any idea appreciated.
Thx Michael
From what you describe, you should have two tables:
Companies
Shops
Customers should have a primary key, like:
create table Companies (
CompanyId int identity(1, 1) primary key,
Name varchar(255),
. . .
);
Then Shops, should refer back to it:
create table Shops (
ShopId int identity(1, 1) primary key,
CompanyId int references Companies(CompanyId),
. . .
);
Presumably, a shop is only related to one company, so you just fill in Shops.CompanyId when you spot the relationship. Only if there is a many-to-many relationship would you need a junction/association table.

Many-to-Many relationship with same table and with relationship constraint

I have a SellerProduct table. Each row within the table represents product information as offered by a seller. The SellerProduct table has the following columns:
id (serial, pk)
productName (nvarchar(50))
productDescription (ntext)
productPrice (decimal(10,2))
sellerId (int, fk to Seller table)
A product may be the same across sellers, but the productName, productDescription and productPrice can vary per seller.
For example, consider the product TI-89. Seller A may have the the following information for the product:
productName = TI-89 Graphing Calc
productDescription = A graphing calculator that...
productPrice 65.12
Seller B may have the the following information for the product:
productName = Texas Instrument's 89 Calculator
productDescription = Feature graphing capabilities...
productPrice 66.50
Admin users will be required to identify that products are the same across various sellers.
I need a way to capture this information (i.e. products are the same across sellers). I could create another table called SellerProductMapper as follows:
sellerProductId1 (int, pk, fk to SellerProdcut table)
sellerProductId2 (int, pk, fk to SellerProdcut table)
The problem with this approach is that it permits sellerProductId1 and sellerProductId2 to be from the same seller for a given row. That should not be allowed.
How can I capture this many-to-many relationship while enforcing this constraint?
You need something that you don't currently have: a "Product Identity" table. If I were designing it, it would have a product ID, Manufacturer's product code, and manufacturer's description. Then the entries in SellerProduct would reference the seller and the product, and you could enforce the constraint with a unique index on the combination of seller and product.
You are coming across your issue because you actually have a more serious data problem with how your table design is laid out.
Your id field does not uniquely identify your data; Making sure every column is dependent on this field is paramount to proper normalization. You should never be in the situation where you need a human pair of eyes to identify two different pieces of data which actually represent the same thing. If I had to guess that id field is probably just an incremented key... ditch this for a truly unique identifier... such as composite key of the manufacturer and the manufacturer's serial number so you know you cannot have two of the same product
Your sellerID field belongs in a different table entirely. A product is just that... a single entity which represents an object. A seller on the other hand is a separate entity that provides a product for sale. Since a seller can have many products and a product can be sold by many sellers, you need a bridge entity (aka a composite entity) to eliminate the many-to-many relationship. If you split the SellerID info from your product table you will have something like this:
Product Table
serialnumber pk
manufacturer pk
productName
productDescription
SellerProducts Table (bridge entity between product and seller)
sellerID pk
manufacturer pk
serialnumber pk
Price
Seller Table
sellerID pk
Name
Location
Other seller based info, etc...
This information is more normalized with productName and productDescription dependent on the primary key of the Product table and price dependent on the primary key of the SellerProducts table.
Unfortunately, cleaning up your data will most likely prove to be tedious... but unless you address this normalization issue now, your problems will only keep compounding until the database is impossible to maintain.

valid schema for company and suppliers and clients?

I am having a problem in modeling relation between a company and suppliers and clients. Basically in my system the supplier and the client are companies too so I made this schema:
table.company:
id
name
//other fields
table.company_suppliers:
company_id FK table.company.id
supplier_id FK table.company.id
table.company_clients:
company_id FK table.company.id
client_id FK table.company.id
Is this ok?
I would use only one table which will contains all the company and a bit field (called by instance Supplier )which will tell you which are are suppliers too.
Company
Id
Name
IsSupplier (bit)
Fk_IdSupplier --it will relate this supplier to a company on the same table
Or you can create a junction table (many to many)
Company
Id
Name
IsSupplier (bit)
CompanySupplier
fk_IdCompany
fk_IdSupplier
Your basic insight is right--you don't want unrelated tables of clients and suppliers. But you have too many ID numbers.
create table companies (
company_id integer primary key,
company_name varchar(35) not null
);
create table suppliers (
supplier_id integer primary key references companies (company_id)
-- Other supplier columns go here.
);
create table clients (
client_id integer primary key references companies (company_id)
-- Other client columns go here.
);
If you're using MySQL, you'll need to adjust the syntax a little. MySQL doesn't support all the standard SQL syntax for declaring primary keys and foreign keys.

Storing invoices in a database

I am making a piece of invoicing software and I want it to save each individual invoice.
The user creates invoices by selecting a customer, as well as however many items are being billed to the customer. Seeing as most invoices will have multiple items, what is the best way to save them to the database without being incredibly redundant? I'm willing to rearrange my entire database if need be.
My tables look like this:
Customers Table:
Id / Primary key
FullName
Address
Phone
Items Table (a table of products offered):
Id / Primary key
ItemName
Price
Description
Invoices Table (saved invoices):
Id / Primary key
CustId / Foreign key is Id in Customer table
ItemId / Foreign key is Id in Item table
Notes
You need another table to store invoices (what you call Invoices now actually stores invoice items).
Customer
id
name
etc.
Item
id
name
etc.
Invoice
id
cust_id
date
InvoiceItem
id
inv_id
item_id
This is the classic way of modeling a many to many relationship using a junction table (i.e. InvoiceItem).
It looks like you will actually want a 4th table to join them. To normalize your data, only keep on each line things that are specific to that invoice
Invoices table
Id / Primary key
CustId / Foreign key is Id in Customer table
Notes
Invoice Items table
InvoiceId
ItemId

how do i create this association

i have the following 2 sql server tables
Products
locationCode (PK), prodId (PK), productName
---------------------------------
AUG, 1, Widget
ATL, 1, Widget
Categories
prodId (PK) catId (PK), catName
----------------------------------
1, 1, WidgetsCategory
1, 1, WidgetsCategory
What would I need to do to create an association where a single product can have many categories given the required fields and (PK) Primary keys?
Create one more table that relates products to categories.
This table should contain the key of products and a foreign key (category id).
In your original question you don't mention whether the location code matters or not. You also don't mention if this is a 1-N or M-N type relationship.
Provide a bit more detail to get additional help.
When you normalize your tables you ensure every table has fields related with only itself (unless of course you are creating that relationship and you store the keys to make that relationship).
Your categories table should only include categories, and should not have anything to do with a product. Once you establish a Category entity, you then relate that category to another product, via another table.