how do i create this association - sql

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.

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.

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.

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.

The correct database schema for one-to-many relationship

I’m building a hobby site about cars. If a user clicks on a car I want to display a list of similar cars for the chosen car.
I have a main table witch stores the basic information about each car, CarDataMain, two of the columns in the table are CarID (Pk) and SimilarCarsID (Fk).
I have another table called “SimilarCars”, it has three columns; SimilarCarsID (Pk), CarGroupID and CarID.
So the SimilarCarsID-column in the SimilarCars-table has a relationship with the column SimilarCarsID in the CarDataMain-table.
Is this the correct approach, or “best practice”?
Each car can only belong to one CarGroup (CarGroupID).
Another solution would be to create a third table witch holds the relationship between CarDataMain and SimilarCars-data, but as there is a one-to-many relationship I guess this is over kill? That way I could however put the same foreign key-value in CarDataMain for all cars witch belong to the same CarGroup, witch somehow feels appealing…
A third solution would be to skip the SimilarCarsID column in CarDataMain and make the CarID a foreign key in the SimilarCars table, if you understand what I mean. But I guess there are some drawbacks with that solution…
Sorry for newbie questions (and if this question has been up before), but I want to get it right before I start :)
Ludde
Note: re-written
Design tables that describe things like Car, Group, others?
Use "join tables" to give the desired one-to-many relationships.
Tables
CarID - primary key
Group
GroupID - primary key.
Name - the name of the group.
The GroupID may not be necessary. If Name is unique then use that as the primary key.
CarGroup
CarID - foreign key to Car Table
GroupID - foreign key to Group table
This is a join table. Here you can map a given car to many groups, and map a given group to many cars.
SimilarCar
I may be misunderstanding, but is seems like you want to match cars as similar, for no particular reason. If you want to match by group, that is above; and if you want "these 2 cars are similar, period", here you go. This is not mutually exclusive to the groups.
CarID - FK to Car table
SimilarCarID - Fk to Car table
A constraint so CarId cannot match SimilarCarID -- unless you do want a car to be similar to itself. But if so then just read the car table instead.
I think your concepts need to be cleared up first. Isn't a "similar car" a car that is in the same "group"? If so, you only need 1 term. Since "group" is a reserved word it is better to use something else.
I would go with the term "category". So my Cars table would have a CategoryId column. Picture the page on the front-end where someone would add a new car, wouldn't they have a drop down list to select the Category?
So my model would be:
Cars
-Id (PK)
-Name
-CategoryId (FK to Categories)
...
Categories
-Id (PK)
-Name

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.