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

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.

Related

Adding Derived Attribute To An Entity With Sqlite3

Hello I have 2 entities that are CUSTOMER and PRODUCT at my Entity Relation Diagram(ER).
CUSTOMER and PRODUCT has a M to N relationship which is RATE and this relationship has 2 attributes which are Comment and Rate.
My PRODUCT entity has a derived attribute named Rating-avg which is the average rating of the product, being rated by the CUSTOMER's.
I don't know and can't find how to add the derived attribute to the table while creating it or altering it.
I would be really glad if someone could help.
I am using SQLite3(3.25.2) and SQLiteStudio(3.2.1) (The latest versions up to date.).
You would use a third table, which is called a "junction" or "association" table:
create table CustomerProducts (
CustomerProductId int primary key,
CustomerId int references customers(CustomerId),
ProductId int products(productId),
Rate ?, -- unclear what the type is
Comment text
);
You could name the table Rate, if you like. I typically name association tables after the two tables involved in the relationship, unless it is an entity itself.

How do I fix the following many to many relationship?

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.

Unsure if my ER Diagram to relational model is correct

Ok, I'm brand new to SQL etc so apologies if this is totally wrong..
I have designed an ER Model which I feel is right and I am trying to convert it to relational model and want any advice as to where I am gone wrong on converting it or any tips. Racking my brain.
As I believe it..
1-1 relationships
entities are either combined or the primary key of one entity type is placed as a foreign key in the other relation.
1-m relationships
The primary key from the `one side' is placed as a foreign key in the many side.
m-n relationships
A new relation is created with the primary keys from each entity forming a composite key.
multivalue attributes
a new table is created, primary key used from 1st table and attribute used in the second table alognside primary key.
So here's my go at Relational model, PK in bold, FK in italics
USER:
USERID FNAME LNAME USERNAME PASSWORD USERTYPE EMAIL
CUSTOMER:
USERID, CUST_ID, BIO
ADMIN:
USERID ADMIN_ID
ARTIST
USERID, ARTIST_ID, BIO REC_ID
PRODUCER:
PROD_ID, Name, Email
RECORD LABEL:
RECORD_ID , NAME, DESCRIPTION
ALBUM:
ALBUMID NAME , COST, TITLE, NOOFSONGS
TRACK:
TRACK ID, NAME, COST, TITLE, DESCRIPTION
TRACK REVIEW: DEPENDENT on TRACK SO TRACK ID comes into this table =
REVIEW_ID(PK), TRK_ID(PK) NAME
TRACK PURCHASE TABLE (USER id comes into this table as foreign key)
TrackPuchaseID user_id, date
ALBUM PURCHASE TABLE
AlbumPuchaseID user_id, date, quantity
GENRE TABLE?:
Not sure??
BPM: is mutli value atribute so becoems seperate table so it.s
GenreID BPM
I know this all might be wrong. but any help would be great.. with explanation which should be FK or composite PK etc or what tables I am missing..
On album purchase you should have: user_id, date, album_id.
At track purchase I don't see why you care about the quantity and
you're missing the track_id.
review, track, album, user should all include a date. Might
be as well interesting to add an last_update_date to the artist
and customer.
review should include an user_id.
I guess there's other thing left. You will need an Invoice / Invoice_Purchase table to be able to say "customer xyz bought the items 1,2,3,4...", it should be like:
Table Invoice
invoice_id
user_id
date
status
Table Invoice_Purchase
invoice_id // Id of the invoice
purchase_type // the type of the purchase (for eg. 0 means track and 1 means album)
Maybe you should also add a status to your albuns and tracks, this way you can set if a item can be bought or not. And yes, you shouldn't delete them because you'll have the old invoices relaying on it...
Anyways, you should consider later using a software like Navicat do draw the relation part and deploy your DB.
From an initial look, here are some of my impressions, in no particular order.
1-1 relationships: not only is the PK of the entity defined as a FK in the related table, it is also the related table's PK. This preserves the unity of the relationship.
multivalue attributes: in other words, a 1-m relationship.
There is no reason to have separate ID values for Customer, Admin or Artist. In fact, call them all ID. I would say this is a m-1 relationship as a user could be both a customer and an artist. But the relationship between User table and the others individually are 1-1.
Isn't Track related to Album? So wouldn't AlbumID be a Track attribute?
Purchase tables should have CustID not UserID and be FK to Customer table. This enforces the need that a purchaser be defined as a customer.
Genre could be an attribute of track or album or both. An album could be generally "Country" but have a "Blues" track, a "Pop" track, etc.
Same for producer. There will be an album producer but could be one or more tracks produced by someone else.
Same for artist. There may be one artist for the entire album but what about "The Greatest Top 40 Hits of the 1980s"?
You may want an intersection table between Artist and Label. A label can sign up many artists and an artist could work for many labels (though generally not at the same time).
I have no idea what a BPM is.
That should keep you busy for a while.

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.