-- Primary Table. Intuitively you may want to add a foreign key reference here to emproductsold for all sales per unique employee in this table, but that would
-- not work. Instead you have to think in reverse (many to 1 relationship) and specify the foreign key information in the secondary table that will have many
-- rows tied to a single employee in this primary table.
CREATE TABLE employee (
id INT NOT NULL,
empname VARCHAR(25),
empage INT,
empgender VARCHAR(1) NOT NULL,
empsalary INT,
PRIMARY KEY (id)
);
-- Secondary Table for JOIN queries. This table has many rows that correspond to a single employee row in the Primary Table. Notice the foreign key is defined
-- here and links to the primary table's primary key.
CREATE TABLE emproductsold (
id INT NOT NULL,
eid INT NOT NULL,
salesyear INT NOT NULL,
salesunitsold INT,
salestoproduct VARCHAR(25),
PRIMARY KEY (id),
FOREIGN KEY (eid) REFERENCES employee (id)
);
-- Populate Primary Table
INSERT INTO employee(id, empname, empage, empgender, empsalary) VALUES (1, 'Snappy', 32, 'm', 20500);
INSERT INTO employee(id, empname, empage, empgender, empsalary) VALUES (2, 'Jimmy', 41, 'm', 18890);
INSERT INTO employee(id, empname, empage, empgender, empsalary) VALUES (3, 'Angie', 24, 'f', 26720);
-- Populate Secondary Table
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (1, 1, 2020, 5, 'Hot Hat');
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (2, 2, 2020, 3, 'Paper Ream');
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (3, 3, 2021, 4, 'Hot Hat');
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (4, 2, 2021, 6, 'Beakers');
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (5, 1, 2021, 12, 'Beakers');
INSERT INTO emproductsold(id, eid, salesyear, salesunitsold, salestoproduct) VALUES (6, 3, 2020, 2, 'Paper Ream');