Adding Derived Attribute To An Entity With Sqlite3 - sql

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.

Related

SQL relationship between a primary key column and the same column

In an existing SQL Server database, someone has defined the following:
Table Customer has a CustomerID column which is also identity. Then they have defined a relationship where Customer.CustomerID is primary key and Customer.CustomerID is also foreign key. I.e. the relationship points back to the same table and same column.
What is the purpose of this? Seems entirely pointless to me, so I plan to remove this relationship from the DB.
The relation is called a recursive association or reflexive relationship, you will need this type of relationship when you need to present a relationship between two or more elements of the same type.
For example: for presenting a relationship between employees, you could create two tables Employee and Manager. But because the manager is also an employee, you won't need two tables. So we create a recursive association that point for the same entity.
More about recursive association
UPDATE
Setting a column as PK and FK at the same time could also represent the concept of inheritance.
For example:
class Person {
int ID;
string name;
}
class Customer extends Person {
String workPlace;
}
That would result the tables Person and Customer as listed below:
Person
------------
int id (PK)
string name
Employee
--------------
int id (PK, FK)
string workPlace

ER relational Database coding containg weak entity

So I'm designing a relational database that involves movies, theatres, stands that sell products/souvenirs. Here is the part of the issue that is confusing me:
"...
A movie theatre consists of an identifier, name, address (street,
city, province), and the total number of screens in the theatre.
...
A concession stand is a kiosk that sells products in theatres. The database records the type of concession stand: either food or souvenir (but not both). Products consists of a unique ’stock keeping unit’ (SKU) identifier, the name of the product, the category (e.g., candy, souvenir, popcorn, beverage, toy), and the price of the product (in CAD). Every concession stand must contain at least one product. Concession stands are located only in theatres, and a theatre can have many concession stands within it.
..."
Now I know that concession stand is a weak entity and it has 2 relationships: one with products entity and one with theatre entity. Now both the relationships are going to need to use the type of stand + the primary key of either of the 2 other entities: IS from theatre and SKUID from product.
create table HasStand(
TheatreID integer not null,
type varchar(20) not null check (type = 'food' or type = 'souvenir'),
primary key (TheatreID, type),
foreign key (TheatreID) references Theatre (ID) on delete cascade
);
create table StandSells(
ProductID integer not null,
type varchar(20) not null check (type = 'food' or type = 'souvenir'),
primary key (ProductID, type),
foreign key (ProductID) references Products (SKUID) on delete cascade
);
It says that a theatre can have many concession stands i.e. multiple stands that are food and/or multiple stands that are souvenir.
My question is: How can I find out where was a certain product sold? at which theatre? I know I can use the product SKUID to find out type of stand and use the theatreID to find that stand with that type but I have a situation here where a theatre might have 2 food stands so using the SKUID I find out oit is a food type stand and when I use the TheatreID i find out that there are 2 stands that are food type thus hitting a dead end; i cant find out which one of them sold that item?
p.s. I cannot use a unique IDs for the concession stands at all, only type.
Any idea?
I would suggest the following tables assuming you really can't use a ConcessionStand unique entity. The solution uses the receipt for the sale to track back to the theater and ConcessionStandType but still isn't quick perfect. In other words once a sell is made a ReceiptId gets associated to the respective place it was pulled from using the unique ProductSKUId.
NOTE: I am also assuming each stand has unique product SKUs
Theater
TheaterId - PrimaryKey
...other attributes as appropriate
Product
ProductSKUId - PrimaryKey
...other attributes as appropriate
ConcessionStandInventory
TheaterID - ForeignKey
ProductSKUId - ForeignKey
ConcessionTypeID - ForeignKey
ReceiptId nullable
Receipt
ReceiptId - PK
TheaterID
ProductSKUId
ConcessionTypeID
ConcessionType
ConcessionTypeID
ConcessionTypeDesc

A table with all attributes making the primary key

I have two tables: Student and Shop and I would like to record information about which student visited which shop and if the number of visits is above n, they should received a discount:
This is how I did it:
All of attributes (studentID, shopID, time, date) in table StudentShop makes the primary key for this table. I just wanted to know if this design is good?
As relation between entieties Student - Shop is many to many relationship,
it is always implemented using associative table (consists of primary keys from both relations), so StudentShop table - is good choice for implementation of such relation.

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.

If I have two tables in SQL with a many-many relationship, do I need to create an additional table?

Take these tables for example.
Item
id
description
category
Category
id
description
An item can belong to many categories and a category obviously can be attached to many items.
How would the database be created in this situation? I'm not sure. Someone said create a third table, but do I need to do that? Do I literally do a
create table bla bla
for the third table?
Yes, you need to create a third table with mappings of ids, something with columns like:
item_id (Foreign Key)
category_id (Foreign Key)
edit: you can treat item_id and category_id as a primary key, they uniquely identify the record alone. In some applications I've found it useful to include an additional numeric identifier for the record itself, and you might optionally include one if you're so inclined
Think of this table as a listing of all the mappings between Items and Categories. It's concise, and it's easy to query against.
edit: removed (unnecessary) primary key.
Yes, you cannot form a third-normal-form many-to-many relationship between two tables with just those two tables. You can form a one-to-many (in one of the two directions) but in order to get a true many-to-many, you need something like:
Item
id primary key
description
Category
id primary key
description
ItemCategory
itemid foreign key references Item(id)
categoryid foreign key references Category(id)
You do not need a category in the Item table unless you have some privileged category for an item which doesn't seem to be the case here. I'm also not a big fan of introducing unnecessary primary keys when there is already a "real" unique key on the joining table. The fact that the item and category IDs are already unique means that the entire record for the ItemCategory table will be unique as well.
Simply monitor the performance of the ItemCategory table using your standard tools. You may require an index on one or more of:
itemid
categoryid
(itemid,categoryid)
(categoryid,itemid)
depending on the queries you use to join the data (and one of the composite indexes would be the primary key).
The actual syntax for the entire job would be along the lines of:
create table Item (
id integer not null primary key,
description varchar(50)
);
create table Category (
id integer not null primary key,
description varchar(50)
);
create table ItemCategory (
itemid integer references Item(id),
categoryid integer references Category(id),
primary key (itemid,categoryid)
);
There's other sorts of things you should consider, such as making your ID columns into identity/autoincrement columns, but that's not directly relevant to the question at hand.
Yes, you need a "join table". In a one-to-many relationship, objects on the "many" side can have an FK reference to objects on the "one" side, and this is sufficient to determine the entire relationship, since each of the "many" objects can only have a single "one" object.
In a many-to-many relationship, this is no longer sufficient because you can't stuff multiple FK references in a single field. (Well, you could, but then you would lose atomicity of data and all of the nice things that come with a relational database).
This is where a join table comes in - for every relationship between an Item and a Category, the relation is represented in the join table as a pair: Item.id x Category.id.