Relational Database Design and MySQL

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Keys, Referential Integrity and PHP One to Many on the Web.
Chapter Eight: Database Redesign Database Processing: Fundamentals, Design, and Implementation.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 8-1 David M. Kroenke’s Chapter Eight: Database Redesign Database Processing:
Python Crash Course Databases 3 rd year Bachelors V1.0 dd Hour 3.
Chapter 17 Designing Databases
Data Modelling. EAR model This modelling language allows a very small vocabulary: Just as English has nouns, verbs, adjectives, pronouns.., EAR models.
1 Chapter 2 Reviewing Tables and Queries. 2 Chapter Objectives Identify the steps required to develop an Access application Specify the characteristics.
Structured Query Language SQL: An Introduction. SQL (Pronounced S.Q.L) The standard user and application program interface to a relational database is.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Page 1 ISMT E-120 Introduction to Microsoft Access & Relational Databases The Influence of Software and Hardware Technologies on Business Productivity.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Page 1 ISMT E-120 Desktop Applications for Managers Introduction to Microsoft Access.
MySql In Action Step by step method to create your own database.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
With Microsoft Office 2007 Intermediate© 2008 Pearson Prentice Hall1 PowerPoint Presentation to Accompany GO! with Microsoft ® Office 2007 Intermediate.
With Microsoft Access 2007 Volume 1© 2008 Pearson Prentice Hall1 PowerPoint Presentation to Accompany GO! with Microsoft ® Access 2007 Volume 1 Chapter.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
DAY 15: ACCESS CHAPTER 2 Larry Reaves October 7,
MIS 301 Information Systems in Organizations Dave Salisbury ( )
IE 423 – Design of Decision Support Systems Database development – Relationships and Queries.
Normalization Are we Normal. Normalization Normalization is the process of converting complex data structures into simple, stable data structures It also.
Chapter 6 1 © Prentice Hall, 2002 The Physical Design Stage of SDLC (figures 2.4, 2.5 revisited) Project Identification and Selection Project Initiation.
SQL, Data Storage Technologies, and Web-Data Integration Week 2.
DAY 12: DATABASE CONCEPT Tazin Afrin September 26,
Natural vs. Generated Keys. Definitions Natural key—a key that occurs in the data, that uniquely identifies rows. AKA candidate key. Generated key—a key.
CSCI 3140 Module 3 – Logical Database Design for the Relational Model Theodore Chiasson Dalhousie University.
M1G Introduction to Database Development 2. Creating a Database.
SQL Basics. 5/27/2016Chapter 32 of 19 Naming SQL commands are NOT case sensitive SQL commands are NOT case sensitive But user identifier names ARE case.
Chapter 5 MYSQL Database. Introduction to MYSQL MySQL is the world's most popular open-source database. Open source means that the source code, the programming.
© 2009 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 7 (Part a): Introduction to SQL Modern Database Management 9 th Edition Jeffrey A.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
DAT602 Database Application Development Lecture 2 Review of Relational Database.
Chapter 13 Designing Databases Systems Analysis and Design Kendall & Kendall Sixth Edition.
Relational Databases Charles Severance. Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0.
Physical Database Design Purpose- translate the logical description of data into the technical specifications for storing and retrieving data Goal - create.
Databases.  Question 1: What does SQL stand for? …………………………………………………………………… (1 point)  Question 2: Considering programming paradigms, what kind of language.
Understand Primary, Foreign, and Composite Keys Database Administration Fundamentals LESSON 4.2.
Relational Databases and MySQL. Relational Databases Relational databases model data by storing rows and columns in tables. The power of the relational.
Relational Databases and SQLite
Relational Database Design and MySQL Charles Severance
Working with MySQL A290/A590, Fall /07/2014.
U:/msu/course/cse/103 Day 08, Slide 1 Debrief Homework What problems arose in trying to import the data from Classical_Music.xls?
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
CS320 Web and Internet Programming SQL and MySQL Chengyu Sun California State University, Los Angeles.
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.
1 The Relational Data Model David J. Stucki. Relational Model Concepts 2 Fundamental concept: the relation  The Relational Model represents an entire.
Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,
Relational Databases Charles Severance Relational Databases Relational databases model data by storing.
Databases.
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
INLS 623– Database Systems II– File Structures, Indexing, and Hashing
SQL – CRUD.
Relational Databases and SQLite
Database Keys and Constraints
Lecturer: Mukhtar Mohamed Ali “Hakaale”
Teaching slides Chapter 8.
CS122 Using Relational Databases and SQL
Views.
CS3220 Web and Internet Programming SQL and MySQL
Chapter 17 Designing Databases
CS122 Using Relational Databases and SQL
CS1222 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
CS3220 Web and Internet Programming SQL and MySQL
CS122 Using Relational Databases and SQL
Presentation transcript:

Relational Database Design and MySQL Charles Severance www.php-intro.com

Complex Data Models and Relationships http://en.wikipedia.org/wiki/Relational_model

Database Design Database design is an art form of its own with particular skills and experience Our goal is to avoid the really bad mistakes and design clean and easily understood databases Others may performance tune things later Database design starts with a picture...

www.tsugi.org

www.sakaiproject.org

Building a Data Model Drawing a picture of the data objects for our application and then figuring out how to represent the objects and their relationships Basic Rule: Don’t put the same string data in twice - use a relationship instead When there is one thing in the “real world” there should be one copy of that thing in the database

Track Len Artist Album Genre Rating Count

For each “piece of info”... Album Is the column an object or an attribute of another object? Once we define objects we need to define the relationships between objects. Len Genre Artist Rating Track Count

Track Rating Len Count Artist Track Album belongs-to Artist Album Genre belongs-to Len Rating Count belongs-to Genre

Track Artist Rating belongs-to Len Count Album belongs-to belongs-to Genre

Representing Relationships in a Database

What album does this song “belong to”?? We want to keep track of which band is the “creator” of each music track... What album does this song “belong to”?? Which album is this song related to?

Database Normalization (3NF) There is *tons* of database theory - way too much to understand without excessive predicate calculus Do not replicate data - reference data - point at data Use integers for keys and for references Add a special “key” column to each table which we will make references to. http://en.wikipedia.org/wiki/Database_normalization

Integer Reference Pattern We use integer columns in one table to reference (or lookup) rows in another table. Artist Album

Terminology of Keys Finding our way around....

Three Kinds of Keys Album id title artist_id ... Primary key - generally an integer auto-inrcement field Logical key - What the outside world uses for lookup Foreign key - generally an integer key point to a row in another table Album id title artist_id ...

Primary Key Rules User Best practices id Never use your logical key as the primary key Logical keys can and do change albeit slowly Relationships that are based on matching string fields are far less efficient than integers performance-wise User id login password name email created_at modified_at login_at

Foreign Keys Artist Album artist_id album_id name title ... artist_id A foreign key is when a table has a column that contains a key which points the primary key of another table. When all primary keys are integers, then all foreign keys are integers - this is good - very good If you use strings as foreign keys - you show yourself to be an uncultured swine Artist artist_id name ... Album album_id title artist_id ...

Relationship Building (in tables)

Track Artist Rating belongs-to Len Count Album belongs-to belongs-to Genre

Track track_id Album title album_id rating title len count album_id belongs-to Track Title Album Rating Len Count Track track_id Album title Table Primary key Logical key Foreign key album_id rating title len count album_id

Naming FK artist_id is a convention. Track Artist track_id artist_id Album title name album_id rating title len artist_id Table Primary key Logical key Foreign key count album_id genre_id Genre genre_id Naming FK artist_id is a convention. name

Creating our Music Database CREATE DATABASE Music DEFAULT CHARACTER SET utf8; USE Music;

CREATE TABLE Artist ( artist_id INTEGER NOT NULL AUTO_INCREMENT KEY, name VARCHAR(255) ) ENGINE = InnoDB; CREATE TABLE Album ( album_id INTEGER NOT NULL AUTO_INCREMENT KEY, title VARCHAR(255), artist_id INTEGER, INDEX USING BTREE (title), CONSTRAINT FOREIGN KEY (artist_id) REFERENCES Artist (artist_id) ON DELETE CASCADE ON UPDATE CASCADE

CREATE TABLE Genre ( genre_id INTEGER NOT NULL AUTO_INCREMENT KEY, name VARCHAR(255) ) ENGINE = InnoDB; CREATE TABLE Track ( track_id INTEGER NOT NULL AUTO_INCREMENT KEY, title VARCHAR(255), len INTEGER, rating INTEGER, count INTEGER, album_id INTEGER, genre_id INTEGER, INDEX USING BTREE (title), CONSTRAINT FOREIGN KEY (album_id) REFERENCES Album (album_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FOREIGN KEY (genre_id) REFERENCES Genre (genre_id) ON DELETE CASCADE ON UPDATE CASCADE

INSERT INTO Artist (name) VALUES ('Led Zepplin'); INSERT INTO Artist (name) VALUES ('AC/DC');

INSERT INTO Artist (name) VALUES ('Led Zepplin'); INSERT INTO Artist (name) VALUES ('AC/DC');

INSERT INTO Genre (name) VALUES ('Rock'); INSERT INTO Genre (name) VALUES ('Metal');

INSERT INTO Album (title, artist_id) VALUES ('Who Made Who', 2); INSERT INTO Album (title, artist_id) VALUES ('IV', 1);

INSERT INTO Track (title, rating, len, count, album_id, genre_id) VALUES ('Black Dog', 5, 297, 0, 2, 1); VALUES ('Stairway', 5, 482, 0, 2, 1); VALUES ('About to Rock', 5, 313, 0, 1, 2); VALUES ('Who Made Who', 5, 207, 0, 1, 2);

We have relationships! Track Album Genre Artist

Using Join Across Tables http://en.wikipedia.org/wiki/Join_(SQL)

Relational Power By removing the replicated data and replacing it with references to a single copy of each bit of data we build a “web” of information that the relational database can read through very quickly - even for very large amounts of data Often when you want some data it comes from a number of tables linked by these foreign keys

The JOIN Operation The JOIN operation links across several tables as part of a select operation You must tell the JOIN how to use the keys that make the connection between the tables using an ON clause

The tables which hold the data select Album.title, Artist.name from Album join Artist on Album.artist_id = Artist.artist_id How the tables are linked What we want to see

select Album.title, Album.artist_id, Artist.artist_id,Artist.name Album.title Album.artist_id Artist.atrist_id Artist.name select Album.title, Album.artist_id, Artist.artist_id,Artist.name from Album join Artist on Album.artist_id = Artist.artist_id

select Track.title, Genre.name from Track join Genre on Track.genre_id = Genre.genre_id

It can get complex... select Track.title, Artist.name, Album.title, Genre.name from Track join Genre join Album join Artist on Track.genre_id = Genre.genre_id and Track.album_id = Album.album_id and Album.artist_id = Artist.artist_id What we want to see The tables which hold the data How the tables are linked

We are telling MySQL to "clean-up" broken references. ON DELETE CASCADE Child We are telling MySQL to "clean-up" broken references. Parent DELETE FROM Genre WHERE name = 'Metal'

DELETE FROM Genre WHERE name = 'Metal' ON DELETE CASCADE DELETE FROM Genre WHERE name = 'Metal'

ON DELETE Choices Default / RESTRICT – Don't allow changes which break the constraint CASCADE – Adjust child rows by removing or updaing to maintian consistency SET NULL – Set the foreign key columns in the child rows to null http://stackoverflow.com/questions/1027656/what-is-mysqls-default-on-delete-behavior

Foreign Key Relationship Types One to many One to one Many to many

Track id Album title id rating title len count album_id belongs-to One Table Primary key Logical key Foreign key id rating title len count album_id Many

One to Many Each Album object may have many Tracks A Track always has one single “Album” An Album may also have zero Tracks (sometimes) Track track_id title album_id ... Album album_id title ...

One to One Each Album object may have a Cover object But a Cover never has more than one Album “One to Zero or One” Album album_id title ... Cover cover_id album_id image ...

Many to Many A User can be a member of many Contexts Context can have many Users We cannot put this in a column of either table We need a separate “relates” table - or join table Membership user_id context_id role ... Context context_id title ... User user_id email ... These many-to-many tables often do not have a separate primary key - the two fields form a composite primary key.

www.tsugi.org

Complexity Enables Speed Complexity makes speed possible and allows you to get very fast results as the data size grows. By normalizing the data and linking it with integer keys, the overall amount of data which the relational database must scan is far lower than if the data were simply flattened out. It might seem like a tradeoff - spend some time designing your database so it continues to be fast when your application is a success

Summary Relational databases allow us to scale to very large amounts of data The key is to have one copy of any data element and use relations and joins to link the data to multiple places This greatly reduces the amount of data which much be scanned when doing complex operations across large amounts of data Database and SQL design is a bit of an art-form