The One-to-Many Relationship Cow of many-well milked and badly fed Spanish proverb.

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
The One-to-Many Relationship. The one-to-many relationship Entities are related to other entities A 1:m relationship.
The single entity. Modeling reality A database must mirror the real world if it is to answer questions about the real world Data modeling is a design.
Concepts of Database Management Seventh Edition
Introduction to Structured Query Language (SQL)
Database Management Fall 2003 The one-to-many relationship Joins, Views, Subqueries & Group by.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Chapter Physical Database Design Methodology Software & Hardware Mapping Logical Design to DBMS Physical Implementation Security Implementation Monitoring.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
Information systems and databases Database information systems Read the textbook: Chapter 2: Information systems and databases FOR MORE INFO...
Structured Query Language
Chapter 4 Relational Databases and Enterprise Systems
INFORMATION TECHNOLOGY IN BUSINESS AND SOCIETY SESSION 16 – SQL SEAN J. TAYLOR.
Introduction to SQL J.-S. Chou Assistant Professor.
This presentation prepared for MIS 421 / MBA 575 at Western Washington University. Material in this presentation drawn from Richard T. Watson, Data Management:
The single entity I want to be alone Greta Garbo.
The single entity I want to be alone Greta Garbo.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
CHAPTER 7 Database: SQL, MySQL. Topics  Introduction  Relational Database Model  Relational Database Overview: Books.mdb Database  SQL (Structured.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Database Management The single entity, the single table, plus some basic SQL.
Component 4/Unit 6f Topic VI: Create simple querying statements for the database The SELECT statement Clauses Functions Joins Subqueries Data manipulation.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
Databases MIS 21. Some database terminology  Database: integrated collection of data  Database Management System (DBMS): environment that provides mechanisms.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
Pasewark & Pasewark 1 Access Lesson 3 Creating Queries Microsoft Office 2007: Introductory.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
SQL LANGUAGE and Relational Data Model TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
In this session, you will learn to: Describe data redundancy Describe the first, second, and third normal forms Describe the Boyce-Codd Normal Form Appreciate.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 16 Using Relational Databases.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
The One-to-Many Relationship Cow of many-well milked and badly fed Spanish proverb.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Teacher Workshop Database Design Pearson Education © 2014.
I want to be alone Greta Garbo
The questing beast Sir Thomas Mallory
The One-to-Many Relationship
© 2016, Mike Murach & Associates, Inc.
Structured Query Language
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

The One-to-Many Relationship Cow of many-well milked and badly fed Spanish proverb

2 The one-to-many relationship Entities are related to other entities A 1:m relationship

3 Hierarchical relationships Occur frequently Multiple 1:m relationships

4 STOCK with additional columns stock stkcodestkfirmstkpricestkqtystkdivstkpenatnameexchrate FCFreedonia Copper United Kingdom1.00 PTPatagonian Tea United Kingdom1.00 ARAbyssinian Ruby United Kingdom1.00 SLGSri Lankan Gold United Kingdom1.00 ILZIndian Lead &Zinc United Kingdom1.00 BEBurmese Elephant United Kingdom1.00 BSBolivian Sheep United Kingdom1.00 NGNigerian Geese United Kingdom1.00 CSCanadian Sugar United Kingdom1.00 ROFRoyal Ostrich Farms United Kingdom1.00 MGMinnesota Gold USA0.67 GPGeorgia Peach USA0.67 NENarembeen Emu Australia0.46 QDQueensland Diamond Australia0.46 IRIndooroopilly Ruby Australia0.46 BDBombay Duck India

5 Create another entity to avoid update anomalies Insert Delete Update

6 Mapping to a relational database Each entity becomes a table The entity name becomes the table name Each attribute becomes a column Add a column to the table at the many end of a 1:m relationship Put the identifier of the one end in the added column

NATION and STOCK nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND

8 Foreign keys A foreign key is a column that is a primary key of another table natcode in stock is a foreign key because natcode is the primary key of nation Record a 1:m relationship

9 Referential integrity constraint For every value of a foreign key there is a primary key with that value For every value of natcode in stock there is a value of natcode in nation A primary key must exist before the foreign key can be defined Must create the nation before its stocks

10 Creating the tables CREATE TABLE nation ( natcodeCHAR(3), natnameVARCHAR(20), exchrateDECIMAL(9,5), PRIMARY KEY (natcode)); CREATE TABLE stock ( stkcodeCHAR(3), stkfirmVARCHAR(20), stkpriceDECIMAL(6,2), stkqtyDECIMAL(8), stkdivDECIMAL(5,2), stkpeDECIMAL(5), natcodeCHAR(3), PRIMARY KEY(stkcode), CONSTRAINT fk_has_nation FOREIGN KEY(natcode) REFERENCES nation(natcode));

11 Representing a 1:m relationship in MySQL Workbench A non-identifying relationship in MySQL Workbench

12 Representing a 1:m relationship in MS Access

Exercise Develop a data model to keep track of a distance runner’s times over various lengths Create the database and add 3 rows for each of 2 athletes 13

14 Join Create a new table from two existing tables by matching on a common column SELECT * FROM stock, nation WHERE stock.natcode = nation.natcode; stkcodestkfirmstkpricestkqtystkdivstkpenatcode natnameexchrate NENarembeen Emu AUS Australia IRIndooroopilly Ruby AUS Australia QDQueensland Diamond AUS Australia BDBombay Duck IND India ROFRoyal Ostrich Farms UK United Kingdom CSCanadian Sugar UK United Kingdom FCFreedonia Copper UK United Kingdom BSBolivian Sheep UK United Kingdom BEBurmese Elephant UK United Kingdom ILZIndian Lead & Zinc UK United Kingdom SLGSri Lankan Gold UK United Kingdom ARAbyssinian Ruby UK United Kingdom PTPatagonian Tea UK United Kingdom NGNigerian Geese UK United Kingdom MGMinnesota Gold US United States GPGeorgia Peach US United States

15 Join Report the value of each stock holding in UK pounds. Sort the report by nation and firm. SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate AS stkvalue FROM stock,nation WHERE stock.natcode = nation.natcode ORDER BY natname, stkfirm; natnamestkfirmstkpricestkqtyexchratestkvalue AustraliaIndooroopilly Ruby AustraliaNarembeen Emu AustraliaQueensland Diamond IndiaBombay Duck United KingdomAbyssinian Ruby United KingdomBolivian Sheep United KingdomBurmese Elephant United KingdomCanadian Sugar United KingdomFreedonia Copper United KingdomIndian Lead & Zinc United KingdomNigerian Geese United KingdomPatagonian Tea United KingdomRoyal Ostrich Farms United KingdomSri Lankan Gold United StatesGeorgia Peach United StatesMinnesota Gold

16 GROUP BY - reporting by groups Report by nation the total value of stockholdings. SELECT natname, SUM(stkprice*stkqty*exchrate) AS stkvalue FROM stock, nation WHERE stock.natcode = nation.natcode GROUP BY natname; natnamestkvalue Australia India United Kingdom United States

17 HAVING - the WHERE clause of groups Report the total value of stocks for nations with two or more listed stocks. SELECT natname, SUM(stkprice*stkqty*exchrate) AS stkvalue FROM stock, nation WHERE stock.natcode = nation.natcode GROUP BY natname HAVING COUNT(*) >= 2; natnamestkvalue Australia United Kingdom United States

Exercise Report the total dividend payment for each country that has three or more stocks in the portfolio 18

Structure of SQL statements 19

Regular expression Search for a string not containing specified characters [^a-f] means any character not in the set containing a, b, c, d, e, or f List the names of nations with non- alphabetic characters in their names SELECT * FROM nation WHERE natname REGEXP '[^a-z|A-Z]'

Regular expression Search for a string containing a repetition {n} means repeat the pattern n times List the names of firms with a double ‘e’. SELECT * FROM stock WHERE stkfirm REGEXP '[e]{2}'

Regular expression Search for a string containing several different specified strings | means alternation (or) List the names of firms with a double ‘s’ or a double ‘n’. SELECT * FROM stock WHERE stkfirm REGEXP '[s]{2}|[n]{2}'

Regular expression Search for multiple versions of a string [ea] means any character from the set containing e and a It will match for ‘e’ or ‘a’ List the names of firms with names that include ‘inia’ or ‘onia’. SELECT * FROM stock WHERE stkfirm REGEXP '[io]nia'

24 Regular expression Find firms with ‘t’ as the third letter of their name. SELECT shrfirm FROM share WHERE shrfirm REGEXP '^(.){2}t'; Find firms not containing an ‘s’ in their name. SELECT shrfirm FROM share WHERE shrfirm NOT REGEXP 's|S';

regexlib.com A library of regular expressions Cheat sheet for creating expressions Regex Tester

Exercise Report the names of nations starting with ‘United’ 26

27 Subqueries A query nested within another query Report the names of all Australian stocks. SELECT stkfirm FROM stock WHERE natcode IN (SELECT natcode FROM nation WHERE natname = 'Australia'); stkfirm Narembeen Emu Queensland Diamond Indooroopilly Ruby

28 Correlated subquery Solves the inner query many times Find those stocks where the quantity is greater than the average for that country. SELECT natname, stkfirm, stkqty FROM stock, nation WHERE stock.natcode = nation.natcode AND stkqty > (SELECT AVG(stkqty) FROM stock WHERE stock.natcode = nation.natcode); natnamestkfirmstkqty AustraliaQueensland Diamond89251 United KingdomBolivian Sheep United KingdomRoyal Ostrich Farms United StatesMinnesota Gold Correlated subqueries can be resource intensive

Correlated subquery nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND SELECT natname, stkfirm, stkqty FROM stock, nation WHERE stock.natcode = nation.natcode AND stkqty > (SELECT AVG(stkqty) FROM stock WHERE stock.natcode = nation.natcode);

Correlated subquery nation natcodenatnameexchrate UKUnited Kingdom1.00 USAUnited States0.67 AUSAustralia0.46 INDIndia stock stkcodestkfirmstkpricestkqtystkdivstkpenatcode FCFreedonia Copper UK PTPatagonian Tea UK ARAbyssinian Ruby UK SLGSri Lankan Gold UK ILZIndian Lead &Zinc UK BEBurmese Elephant UK BSBolivian Sheep UK NGNigerian Geese UK CSCanadian Sugar UK ROFRoyal Ostrich Farms UK MGMinnesota Gold USA GPGeorgia Peach USA NENarembeen Emu AUS QDQueensland Diamond AUS IRIndooroopilly Ruby AUS BDBombay Duck IND SELECT natname, stkfirm, stkqty FROM stock, nation WHERE stock.natcode = nation.natcode AND stkqty > ;

Exercise Report the country, firm, and stock holding for the maximum quantity of stock held for each country 31

32 Views - virtual tables An imaginary table constructed by the DBMS when required Only the definition of the view is stored, not the result CREATE VIEW stkvalue (nation, firm, price, qty, exchrate, value) AS SELECT natname, stkfirm, stkprice, stkqty, exchrate, stkprice*stkqty*exchrate FROM stock, nation WHERE stock.natcode = nation.natcode;

33 Views - querying Query exactly as if a table SELECT nation, firm, value FROM stkvalue WHERE value > ; nationfirmvalue United KingdomFreedonia Copper United KingdomPatagonian Tea United KingdomAbyssinian Ruby United KingdomSri Lankan Gold United KingdomIndian Lead & Zinc United KingdomBolivian Sheep United KingdomNigerian Geese United KingdomCanadian Sugar United KingdomRoyal Ostrich Farms United StatesMinnesota Gold United StatesGeorgia Peach AustraliaNarembeen Emu AustraliaQueensland Diamond AustraliaIndooroopilly Ruby

34 Why create a view? Simplify query writing Calculated columns Restrict access to parts of a table

Exercise Create a view for dividend payment 35

36 Summary New topics 1:m relationship Foreign key Correlated subquery GROUP BY HAVING clause View