SQL8


More Than One Tables

Our example so far involves only one table “products“. A practical database contains many related tables.+
Products have suppliers. If each product has one supplier, and each supplier supplies only one product (known as one-to-one relationship), we can simply add the supplier’s data (name, address, phone number) into the products table. Suppose that each product has one supplier, and a supplier may supply zero or more products (known as one-to-many relationship). Putting the supplier’s data into theproducts table results in duplication of data. This is because one supplier may supply many products, hence, the same supplier’s data appear in many rows. This not only wastes the storage but also easily leads to inconsistency (as all duplicate data must be updated simultaneously). The situation is even more complicated if one product has many suppliers, and each supplier can supply many products, in amany-to-many relationship.+

One-To-Many Relationship

Suppose that each product has one supplier, and each supplier supplies one or more products. We could create a table called suppliers to store suppliers’ data (e.g., name, address and phone number). We create a column with unique value called supplierID to identify every suppliers. We set supplierID as the primary key for the table suppliers (to ensure uniqueness and facilitate fast search).+
To relate the suppliers table to the products table, we add a new column into the products table – the supplierID. We then set the supplierID column of the products table as a foreign key references the supplierID column of the suppliers table to ensure the so-called referential integrity.+
Database: felightlabs
Table: suppliers
supplierID
INT
name
VARCHAR(30)
phone
CHAR(8)
501ABC Traders88881111
502XYZ Company88882222
503QQ Corp88883333
Database: felightlabs
Table: products
productID
INT
productCode
CHAR(3)
name
VARCHAR(30)
quantity
INT
price
DECIMAL(10,2)
supplierID
INT
(Foreign Key)
2001PECPencil 3B5000.52501
2002PECPencil 4B2000.62501
2003PECPencil 5B1000.73501
2004PECPencil 6B5000.47502
We need to first create the suppliers table, because the products table references the suppliers table. The suppliers table is known as the parent table; while the products table is known as the childtable in this relationship.+
one-to-Many1+

Comments

Popular posts from this blog

Java Beginners Tutotrial