Banner

 

4 - The One-to-Many Relationship

Answers to exercises

1.
Draw data models for the following situations. In each case, make certain that you show the attributes and feasible identifiers:
1a.
A farmer can have many cows, but a cow belongs to only one farmer.
1b.
A university has many students, and a student can attend at most one university.
1c.
An aircraft can have many passengers, but a passenger can be on only one flight at a time.
1d.
A nation can have many states and a state many cities.
1e.
An art researcher has asked you to design a database to record details of artists and the museums in which their paintings are displayed. For each painting, the researcher wants to know the size of the canvas, year painted, title, and style. The nationality, date of birth, and death of each artist must be recorded. For each museum, record details of its location and specialty, if it has one.
2.
Report all values in British pounds:
2a.
Report the value of stocks listed in Australia.
SELECT stkcode, stkfirm, stkprice*stkqty*exchrate 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode 
WHERE natname = 'Australia';
2b.
Report the dividend payment of all stocks.
SELECT stkcode, stkfirm, stkdiv*stkqty*exchrate 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode; 
stkfirm
expr1001
Freedonia Copper 19373.36
Patagonian Tea 31587.5
Abyssinian Ruby 29053.2
Sri Lankan Gold 88086.24
Indian Lead & Zinc 19170
Burmese Elephant 1547.13
Bolivian Sheep 412386.84
Nigerian Geese 20702.64
Canadian Sugar 11790
Royal Ostrich Farms 3704769
Minnesota Gold 546801.753620505
Georgia Peach 51902.6232928634
Narembeen Emu 20984.7403806746
Queensland Diamond 20527.7303723842
Indooroopilly Ruby 12913.8102342635
Bombay Duck 3816.30966435
2c.
Report the total dividend payment by nation.
SELECT natname, SUM(stkdiv*stkqty*exchrate) 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode GROUP BY natname;
2d.
Create a view containing nation, firm, price, quantity, exchange rate, value, and yield.
CREATE VIEW yield(nation, firm, price, qty, exchrate, value, yield) 
AS SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate,stkdiv/stkprice*100*exchrate 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode;

MS Access does not support the SQL CREATE VIEW statement. However, you can create the equivalent of a view by saving a query and then using the name of the query as a table name. In other words, in MS Access a saved query is a view. So you might write the following:

2e.
Report the average yield by nation.
SELECT natname, AVG(stkdiv/stkprice*exchrate*100) 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode GROUP BY natname;
2f.
Report the minimum and maximum yield for each nation.
SELECT natname, MIN(stkdiv/stkprice*100), MAX(stkdiv/stkprice*100) 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode GROUP BY natname;
natname
expr1001
expr1002
Australia 3.14070351758794 8.10372771474878
India 3.91389432485323 3.91389432485323
United Kingdom 4.14833438089252 14.2857142857143
United States 1.85632077222944 8.51063829787234
2g.
Report the nations where the average yield of stocks exceeds the average yield of all stocks.
SELECT natname, AVG(stkdiv/stkprice*100) 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode GROUP BY natname HAVING AVG(stkdiv/stkprice*100) > (SELECT AVG(stkdiv/stkprice*100) FROM stock);
3.
How would you change the queries in exercise 4 -2 if you were required to report the values in American dollars, Australian dollars, or Indian rupees?

All exchange rates in nation are based on the UK pound, which as a result has a value of 1.00.

To convert to US dollars, all currency values must be divided by the US exchange rate (0.67 in nation). Similarly, dividing by 0.46 will convert currency values to Australian dollars. Thus, the total value of stocks in US dollars is:

SELECT SUM(stkqty*stkprice*exchrate/0.67) 
FROM stock JOIN nation 
ON stock.natcode = nation.natcode;

The question becomes more taxing when you want to extract the exchange rate from the nation table. Exchange rates vary daily, so the SQL code above is not very useful.

The query would be easy if in one row you had the stock, its exchange rate, and the exchange rate of the currency in which values should be expressed. To get a stock and its exchange rate in one row, you join the two tables and save as tempory table T1. Then you must concatenate to each row the exchange rate of the target currency -- this is done by using a product (see pages 258 of the text). The other difficult part is that you need to use the nation table twice (once for the exchange rate and once for the target currency). This query challenges your skills as this stage, but it is important to know that SQL can handle such requests.

SELECT `Value`/exchrate FROM (SELECT SUM(stkqty*stkprice*exchrate) AS `Value` 
FROM stock JOIN nation
ON stock.natcode = nation.natcode) AS T1, nation
WHERE natname = 'United States';

Now, calculate the value of Australian stocks in Australian dollars.

4.
What is a foreign key and what role does it serve?

A foreign key is used to implement a 1:m relationship. In fact, the foreign key is an extra column which has been added to the table at the many end of the 1:m relationship. This extra column contains the value of the primary key of the table at the one end of the 1:m relationship. Through the foreign key, the two tables can be linked.

5.
What is the referential integrity constraint? Why should it be enforced?

The referential integrity constraint demands that for every foreign key in a table there is a corresponding primary key in another table (later, students will learn it can be in the same table, but at this stage it is easier to handle assuming another table). In other words, for every value of the foreign key, an identical value for the corresponding primary key must exist.

6.
Kisha, against the advice of her friends, is simultaneously studying data management and Shakespearian drama. She thought the two subjects would be an interesting contrast. However, the classes are very demanding and often enter her midsummer dreams. Last night, she dreamed that William Shakespeare wanted her to draw a data model. He explained, before she woke up in a cold sweat, that a play had many characters but the same character never appeared in more than one play.“Methinks,” he said, “the same name may have appeareth more than the once, but twas always a person of a different ilk.” He then, she hazily recollects, went on to spout about the quality of data dropping like the gentle rain. Draw a data model to keep old Bill quiet and help Kisha get some sleep.

The character's name would not be a sufficient identifier since the same character name could be used in many plays. However, each character name is typically only used once in each play. If this is not true for these plays, one would have to create a characterid to uniquely distinguish each character.

7.
An orchestra has four broad classes of instruments (strings, woodwinds, brass, and percussion). Each class contains musicians who play different instruments. For example, the strings section of a full symphonic orchestra contains 2 harps, 16 to 18 first violins, 14 to 16 second violins, 12 violas, 10 cellos, and 8 double basses. A city has asked you to develop a database to store details of the musicians in its three orchestras. All the musicians are specialists and play only one instrument for one orchestra.
8.
Answer the following queries based on the following database for a car dealer:
8a.
What is the personid of Sheila O'Hara?
SELECT personid FROM person 
WHERE `person first` = 'Sheila' 
AND `person last` = "O'Hara"; 
personid
21

Teaching Tip: The class should discuss the problems of handling O'Hara.

8b.
List sales personnel sorted by last name and within last name, first name.
SELECT * FROM person 
ORDER BY `person last`,`person first`;
8c.
List details of the sales made by Bruce Bush.
SELECT cartype, carcost, carsell 
FROM person JOIN car
ON person.personid = car.personid 
WHERE `person first` = 'Bruce' 
AND `person last` = 'Bush';
cartype
carcost
carsell
coupe 15500.00 14750.00
sports 1255.00 1355.00
sedan 950.00 2000.00
8d.
List details of all sales showing the gross profit (selling price minus cost price).
SELECT `person first`, `person last`, carid, carcost, carsell, cartype, carsell-carcost
FROM car JOIN person
ON person.personid = car.personid;
8e.
Report the number of cars sold of each type.
SELECT cartype, COUNT(cartype) 
FROM car GROUP BY cartype;
cartype
expr1001
coupe 2
sedan 5
sports 3
8f.
What is the average selling price of cars sold by Sue Lim?
SELECT AVG(carSELL) 
FROM car JOIN person 
ON car.personid = person.personid 
WHERE `person first` = 'Sue' 
AND `person last` = 'Lim';
8g.
Report details of all sales where the gross profit is less than the average.
SELECT `person first`, `person last`, cartype, carsell-carcost AS profit
FROM car JOIN person
ON person.personid = car.personid
WHERE (carsell-carcost)
< (SELECT AVG(carsell-carcost) FROM car);
person first person last cartype profit
Nolan Haley sedan 295.00
Bruce Bush coupe -750.00
Bruce Bush sports 100.00
Bruce Bush sedan 1050.00
Sue Lim sedan 600.00
Barbara Capelli sedan 500.00
8h.
What was the maximum selling price of any car?
SELECT MAX(carsell) FROM car;
8i.
What is the total gross profit?
SELECT SUM(carsell-carcost) as `Gross profit` FROM car;
Gross profit
11295.00
8j.
Report the gross profit made by each salesperson who sold at least three cars.
SELECT `person first`, `person last`, SUM(carsell-carcost) 
FROM car JOIN person 
ON person.personid=car.personid 
GROUP BY `person first`, `person last` 
HAVING COUNT(*) > 2;
8k.
Create a view containing all the details in the car table and the gross profit.
CREATE VIEW PROFIT(id, type, cost, sell, profit) 
AS SELECT carid, cartype,carcost, carsell,carsell-carcost FROM car; 
9.
Find stocks where the third or fourth letter in their name is an 'm'.
SELECT stkfirm FROM stock WHERE stkfirm REGEXP '^(.){2}m|^(.){3}m';
10.
An electricity supply company needs a database to record details of solar panels installed on its customers’ homes so it can estimate how much solar energy will be generated based on the forecast level of solar radiation for each house’s location. A solar panel has an area, measured in square meters, and an efficiency expressed as a percentage (e.g., 22% efficiency means that 22% of the incident solar energy is converted into electrical energy). Create a data model. How will you identify each home and each panel?

Note: There is a bug in MySQLWorkbench, customerID is part of the key for panel.

 

This page is part of the promotional and support material for Data Management (open edition) by Richard T. Watson
For questions and comments please contact the author
Date revised: 10-Dec-2021