Presentation is loading. Please wait.

Presentation is loading. Please wait.

This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:

Similar presentations


Presentation on theme: "This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:"— Presentation transcript:

1

2 This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., the instructor’s experience, and other sources as noted. Some items © 2006 John Wiley & Sons. All rights reserved.

3 The One-to-Many Relationship; The Many-to-Many Relationship MIS 421 Dr. Steven C. Ross Fall 2011

4 Relationship A relationship exists when there is some logical connection between two entities … where one instance of an entity is somehow related to one or more instances of another (or the same) entity. A relationship exists when there is some logical connection between two entities … where one instance of an entity is somehow related to one or more instances of another (or the same) entity. Most common is the one-to-many relationship. Most common is the one-to-many relationship.

5 Chapter 4 The One-to-Many Relationship “Cow of many – well-milked and badly fed.” Spanish proverb quoted in Watson, p. 89

6 One-to-Many (1:M) Building … Room Building … Room A building has one or more rooms A building has one or more rooms A room is in only one building A room is in only one building Nation … Stock Nation … Stock STOCK *stock code stock name stock price stock quantity stock dividend stock PE NATION *nation code nation name exchange rate

7 Logical Design Modeling* Relationship depicted by a single line Relationship depicted by a single line Relationship name not required Relationship name not required Ordinality (minimum) not shown Ordinality (minimum) not shown “Many” cardinality indicated by crows-foot “Many” cardinality indicated by crows-foot Foreign key not shown Foreign key not shown STOCK *stock code stock name stock price stock quantity stock dividend stock PE NATION *nation code nation name exchange rate * The style used in the Watson book might differ from what you’ve seen before. At this point in the course, we will use a style consistent with the text; be prepared for changes later in the quarter.

8 Rationale behind 1:M If NATION entity did not exist, then exchange rate information would be stored in STOCK and … If NATION entity did not exist, then exchange rate information would be stored in STOCK and … We could not add exchange rate information for a country unless we had a stock from that country (“insert anomaly”). We could not add exchange rate information for a country unless we had a stock from that country (“insert anomaly”). We would lose exchange rate information about a country if we deleted the only stock from that country (“delete anomaly”). We would lose exchange rate information about a country if we deleted the only stock from that country (“delete anomaly”). If the exchange rate for a country changes, we must update every stock record that contains that country’s exchange rate (“update anomaly”). If the exchange rate for a country changes, we must update every stock record that contains that country’s exchange rate (“update anomaly”). STOCK *stock code stock name stock price stock quantity stock dividend stock PE nation name exchange rate

9 Skill Builder* The university architect has asked you to develop a data model to record details of the campus buildings. A building can have many rooms, but a room can be in only one building. Buildings have names, and rooms have a size and a purpose (e.g., lecture, laboratory, seminar). Draw a data model for this situation. The university architect has asked you to develop a data model to record details of the campus buildings. A building can have many rooms, but a room can be in only one building. Buildings have names, and rooms have a size and a purpose (e.g., lecture, laboratory, seminar). Draw a data model for this situation. * From Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., p. 96 ROOM *room number room size room purpose BUILDING *building name

10 Skill Builder (continued) What would you use for the foreign key, and in which entity? What would you use for the foreign key, and in which entity? building name, in ROOM building name, in ROOM abbreviation code, if available, would be better abbreviation code, if available, would be better What would you use as the identifier/PK of ROOM? What would you use as the identifier/PK of ROOM? combination of building name and room number (e.g., PH 244) combination of building name and room number (e.g., PH 244)

11 Creating a Database with a 1:M Relationship Each entity becomes a table; each attribute becomes a column; each identifier becomes a primary key. Each entity becomes a table; each attribute becomes a column; each identifier becomes a primary key. Add a column to the entity at the “many” side … this column contains the identifier (primary key) of the entity at the “one” side. This column is known as a foreign key. Add a column to the entity at the “many” side … this column contains the identifier (primary key) of the entity at the “one” side. This column is known as a foreign key.

12 Referential Integrity The value in the foreign key field must either match a value in the primary key field of the related entity or be null. The value in the foreign key field must either match a value in the primary key field of the related entity or be null. Often, null is not permitted. Often, null is not permitted. Instance in “one” entity must be created before matching instance(s) in “many” entity. Instance in “one” entity must be created before matching instance(s) in “many” entity. Which is why we almost always model the relationship to the many side entity as zero-many Which is why we almost always model the relationship to the many side entity as zero-many

13 CREATE TABLE tblNation ( natcodeCHAR(3), natcodeCHAR(3), natnameVARCHAR(20), natnameVARCHAR(20), exchrateDECIMAL(9,5), exchrateDECIMAL(9,5), PRIMARY KEY (natcode)); CREATE TABLE tblStock ( stkcodeCHAR(3), stkcodeCHAR(3), stkfirmVARCHAR(20), stkfirmVARCHAR(20), stkpriceDECIMAL(6,2), stkpriceDECIMAL(6,2), stkqtyDECIMAL(8), stkqtyDECIMAL(8), stkdivDECIMAL(5,2), stkdivDECIMAL(5,2), stkpeDECIMAL(5), stkpeDECIMAL(5), natcodeCHAR(3), natcodeCHAR(3), PRIMARY KEY(stkcode), CONSTRAINT fk_stock_nation FOREIGN KEY(natcode) REFERENCES tblNation ON DELETE RESTRICT); REFERENCES tblNation ON DELETE RESTRICT); Creating the Database * Modified from Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., p. 94 FK data type, field size must match PK; names do not have to match

14 Querying a Two-Table Database The concept of JOIN: to create a new table from the contents of two tables by matching on a column common to both tables. The concept of JOIN: to create a new table from the contents of two tables by matching on a column common to both tables. The resultant table is transitory … it exists for only the duration of the command unless you explicitly save it. The resultant table is transitory … it exists for only the duration of the command unless you explicitly save it.

15 Two Ways to JOIN Textbook’s method: SELECT * FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode Access-generated: SELECT * FROM tblStock INNER JOIN tblNation ON tblStock.natcode = tblNation.natcode

16 JOIN Considerations You must specify table names, columns to match, and match condition You must specify table names, columns to match, and match condition If FK has same name as PK, field names must be qualified (by table name or alias): tblStock.natcode = tblNation.natcode If FK has same name as PK, field names must be qualified (by table name or alias): tblStock.natcode = tblNation.natcode If you SELECT * If you SELECT * the PK and FK columns will both appear in output the PK and FK columns will both appear in output Number of columns in output = sum of number of columns in both tables Number of columns in output = sum of number of columns in both tables

17 Sample Database The Infinity Symbol denotes “many” The Key Symbol denotes “one”

18 SELECT Command Example I SELECT FirstName,LastName,Rank FROM tblWorker INNER JOIN tblRank ON tblWorker.RankID = tblRank.RankID ON tblWorker.RankID = tblRank.RankID FirstName LastName Rank Jan Zigler Manager Bob Visser Supervisor Lisa Schneider Supervisor Shannon Spicer Lead Billie McMaster Lead Danny Dean Lead James Watts Regular Staff

19 Skill Builder* List each stock name and the country of origin. Order the list by country, then stock name. List each stock name and the country of origin. Order the list by country, then stock name. SELECT stkfirm, natname FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode ORDER BY natname, stkfirm SELECT stkfirm, natname FROM tblStock INNER JOIN tblNation ON tblStock.natcode = tblNation.natcode ORDER BY natname, stkfirm * Developed by Steven C. Ross

20 Reporting by Group The result of a 1:M join is often a lot of repeated data from the 1 table The result of a 1:M join is often a lot of repeated data from the 1 table GROUP BY clause can summarize M table data: GROUP BY clause can summarize M table data: SELECT natname, sum(stkprice*stkqty*exchrate) AS stkvalue FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode GROUP BY natname

21 GROUP BY When the GROUP BY clause is used When the GROUP BY clause is used SELECT clause may contain only SELECT clause may contain only Aggregate functions (COUNT, SUM, AVERAGE, MIN, MAX) Aggregate functions (COUNT, SUM, AVERAGE, MIN, MAX) Fields named in the GROUP BY clause Fields named in the GROUP BY clause

22 SELECT Command Example II SELECT tblRank.RankID, Rank, COUNT(*) AS RankCount FROM tblWorker INNER JOIN tblRank ON tblWorker.RankID = tblRank.RankID ON tblWorker.RankID = tblRank.RankID GROUP BY tblRank.RankID, Rank RankID Rank RankCount 1 Manager 1 2 Supervisor 2 3 Lead 3 4 Regular Staff 5 5 Probationary 2

23 HAVING HAVING applies conditions to groups HAVING applies conditions to groups Can be used only following GROUP BY Can be used only following GROUP BY Usually based on aggregate function result Usually based on aggregate function result SELECT natname, SUM(stkprice*stkqty*exchrate) AS stkvalue FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode GROUP BY natname HAVING COUNT(*) > 1

24 SELECT Command Example III SELECT tblRank.RankID, Rank, COUNT(*) AS RankCount FROM tblWorker INNER JOIN tblRank ON tblWorker.RankID = tblRank.RankID ON tblWorker.RankID = tblRank.RankID GROUP BY tblRank.RankID, Rank HAVING COUNT(*) > 2 RankID Rank RankCount 3 Lead 3 4 Regular Staff 5

25 Skill Builder* Determine how many stocks are in each country. Determine how many stocks are in each country. SELECT natname, COUNT(*) AS CountryCount FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode GROUP BY natname SELECT natname, COUNT(*) AS CountryCount FROM tblStock INNER JOIN tblNation ON tblStock.natcode = tblNation.natcode GROUP BY natname * Developed by Steven C. Ross

26 IN Subqueries Instead of Instead of IN ('val1','val2','val3',…) Use Use IN (SELECT field FROM … ) SELECT stkfirm FROM tblStock WHERE natcode IN (SELECT natcode FROM tblNation WHERE natname LIKE 'Ind%');

27 Correlated Subqueries Subquery that is evaluated for each record in outer query Subquery that is evaluated for each record in outer query SELECT natname, stkfirm, stkqty FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode AND stkqty > (SELECT AVG(stkqty) FROM tblStock ts2 WHERE ts2.natcode = tblNation.natcode);

28 Views A view is a virtual table A view is a virtual table Statement to create view is saved Statement to create view is saved Data returned by view is drawn from base tables at time of execution Data returned by view is drawn from base tables at time of execution View may have different column names than base tables View may have different column names than base tables View may include calculated fields View may include calculated fields Views are a security mechanism when they restrict columns or rows Views are a security mechanism when they restrict columns or rows

29 Creating a View CREATE VIEW vueStkvalue (nation, firm, price, qty, exchrate, value) AS SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode CREATE VIEW vueStkvalue AS SELECT natname AS nation, stkfirm AS firm, stkprice AS price, stkqty AS qty, exchrate, stkprice*stkqty*exchrate AS value FROM tblStock, tblNation WHERE tblStock.natcode = tblNation.natcode

30 Chapter 5 The Many-to-Many Relationship

31 Operationalizing a M:M Convert this → Convert this → To this ↓ To this ↓ SALE *saleno saledate saletext ITEM *itemno itemname itemtype LINEITEM *lineno lineqty SALE *saleno saledate saletext ITEM *itemno itemname itemtype

32 More about M:M Entity in middle is called “associative,” “intersection,” or “linking” entity Entity in middle is called “associative,” “intersection,” or “linking” entity + (not always present) signifies a “weak” or “dependent” entity – relies on another entity for its existence and identification + (not always present) signifies a “weak” or “dependent” entity – relies on another entity for its existence and identification LINEITEM *lineno lineqty SALE *saleno saledate saletext ITEM *itemno itemname itemtype

33 The Associative Entity Contains FKs pointing to each of the original entities Contains FKs pointing to each of the original entities Contains attributes relevant to the combination of the two original entities Contains attributes relevant to the combination of the two original entities Quantity Quantity Date (sometimes) Date (sometimes) Status Status Price (if it varies by transaction) Price (if it varies by transaction)

34 Creating a Database with a M:M Relationship Each entity becomes a table; each attribute becomes a column; each identifier becomes a primary key. Each entity becomes a table; each attribute becomes a column; each identifier becomes a primary key. For each of the original entities, add a column to the associative entity (which is at the “many” side) … this column contains the identifier (primary key) of the entity at the “one” side. This column is known as a foreign key. For each of the original entities, add a column to the associative entity (which is at the “many” side) … this column contains the identifier (primary key) of the entity at the “one” side. This column is known as a foreign key.

35 Skill Builder* A hamburger shop makes several types of hamburgers, and the same type of ingredient can be used with several types of hamburgers. Draw the data model for this situation. A hamburger shop makes several types of hamburgers, and the same type of ingredient can be used with several types of hamburgers. Draw the data model for this situation. * From Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., p. 119 RECIPE *lineno quantity preparation PRODUCT *prodno prodname prodprice INGREDIENT *ingredientno ingredientname

36 Two Ways to JOIN Textbook’s method: SELECT * FROM tblSale, tblLineItem, tblItem WHERE tblSale.saleno = tblLineItem.saleno AND tblLineItem.itemno = tblItem.itemno Access-generated: SELECT * FROM tblSale INNER JOIN tblLineItem ON tblSale.saleno = tblLineItem.saleno INNER JOIN tblItem ON tblLineItem.itemno = tblItem.itemno

37 Sample Database

38 SELECT Command Example IV SELECT FirstName, LastName, StartDate, tblBuilding.BuildingID, City tblBuilding.BuildingID, City FROM tblWorker INNER JOIN tblAssignment INNER JOIN tblAssignment ON tblWorker.WorkerID = tblAssignment.WorkerID ON tblWorker.WorkerID = tblAssignment.WorkerID INNER JOIN tblBuilding INNER JOIN tblBuilding ON tblBuilding.BuildingID = tblAssignment.BuildingID ON tblBuilding.BuildingID = tblAssignment.BuildingID FirstName LastName StartDate BuildingID City Billie McMaster 2006-01-01 00:00:00.000 1 Bellingham Daniel Dean 2006-01-15 00:00:00.000 1 Bellingham Daniel Dean 2006-02-02 00:00:00.000 3 Blaine

39 Existentialism EXISTS (SELECT …) EXISTS (SELECT …) Returns True or False Returns True or False Used in WHERE clause Used in WHERE clause True if the select subquery returns one or more rows True if the select subquery returns one or more rows Same effect can often be achieved by an inner join Same effect can often be achieved by an inner join Examples on next slide …

40 EXISTS SELECT itemname, itemcolor FROM tblItem WHERE itemtype = 'C' AND EXISTS (SELECT * FROM tblLineItem WHERE tblLineItem.itemno =tblItem.itemno); SELECT DISTINCT itemname, itemcolor FROM tblItem INNER JOIN tblLineItem ON tblLineItem.itemno =tblItem.itemno WHERE itemtype = 'C';

41 SELECT Command Example V SELECT FirstName, LastName FROM tblWorker WHERE EXISTS (SELECT * FROM tblAssignment WHERE BuildingID = 3 WHERE BuildingID = 3 AND tblAssignment.WorkerID=tblWorker.WorkerID) AND tblAssignment.WorkerID=tblWorker.WorkerID) FirstName LastName Daniel Dean

42 Skill Builder* Report all red items that have been sold (itemcolor='red'). Write the query twice, once using EXISTS and once without EXISTS. Report all red items that have been sold (itemcolor='red'). Write the query twice, once using EXISTS and once without EXISTS. SELECT itemname, itemcolor FROM tblItem WHERE itemcolor = 'red' AND EXISTS (SELECT * FROM tblLineItem WHERE tblLineItem.itemno =tblItem.itemno); SELECT DISTINCT itemname, itemcolor FROM tblItem INNER JOIN tblLineItem ON tblLineItem.itemno =tblItem.itemno WHERE itemcolor = 'red'; * From Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., p. 120

43 NOT EXISTS Used to search for absence of data Used to search for absence of data Cannot get this answer from an inner join (but an outer join could be used) Cannot get this answer from an inner join (but an outer join could be used) SELECT itemname, itemcolor FROM tblItem WHERE itemtype = 'C' AND NOT EXISTS (SELECT * FROM tblLineItem WHERE tblLineItem.itemno =tblItem.itemno);

44 SELECT Command Example VI SELECT FirstName, LastName FROM tblWorker WHERE NOT EXISTS (SELECT * FROM tblAssignment WHERE BuildingID = 3 WHERE BuildingID = 3 AND tblAssignment.WorkerID=tblWorker.WorkerID) AND tblAssignment.WorkerID=tblWorker.WorkerID) FirstName LastName Jan Zigler Bob Visser Lisa Schneider Shannon Spicer Billie McMaster

45 Skill Builder* Report all red items that have not been sold (itemcolor='red'). Report all red items that have not been sold (itemcolor='red'). SELECT itemname, itemcolor FROM tblItem WHERE itemcolor = 'red' AND NOT EXISTS (SELECT * FROM tblLineItem WHERE tblLineItem.itemno =tblItem.itemno); * From Richard T. Watson, Data Management: Databases and Organization, 5 th Ed., p. 122

46 Universality Find the items that appear in all sales. Find the items that appear in all sales. is the same as Find the items for which there is no sale in which they do not appear. Find the items for which there is no sale in which they do not appear. SELECT itemno, itemname FROM tblItem WHERE NOT EXISTS (SELECT * FROM tblSale WHERE NOT EXISTS (SELECT * FROM tblLineItem WHERE tblLineItem.itemno = tblItem.itemno AND tblLineItem.saleno = tblSale.saleno));

47 More … UNION UNION Combines output of two or more SELECT statements – all non-duplicated rows Combines output of two or more SELECT statements – all non-duplicated rows INTERSECT INTERSECT Combines output of two or more SELECT statements – all common rows Combines output of two or more SELECT statements – all common rows EXCEPT EXCEPT Combines output of two or more SELECT statements – all rows in first statement that are not in second statement Combines output of two or more SELECT statements – all rows in first statement that are not in second statement

48 Next Lecture One-to-One and Recursive Relationships


Download ppt "This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:"

Similar presentations


Ads by Google