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

Slides:



Advertisements
Similar presentations
Keys, Referential Integrity and PHP One to Many on the Web.
Advertisements

Python Crash Course Databases 3 rd year Bachelors V1.0 dd Hour 3.
My CD Database THE BEST Shoemaker, Ray, Gleisberg.
Data Modelling. EAR model This modelling language allows a very small vocabulary: Just as English has nouns, verbs, adjectives, pronouns.., EAR models.
Relational Database Design and MySQL
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
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.
Page 1 ISMT E-120 Introduction to Microsoft Access & Relational Databases The Influence of Software and Hardware Technologies on Business Productivity.
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.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
DAY 15: ACCESS CHAPTER 2 Larry Reaves October 7,
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
MIS 301 Information Systems in Organizations Dave Salisbury ( )
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
INFO 344 Web Tools And Development CK Wang University of Washington Spring 2014.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
SQL pepper. Why SQL File I/O is a great deal of code Optimal file organization and indexing is critical and a great deal of code and theory implementation.
Normalization (Codd, 1972) Practical Information For Real World Database Design.
Chapter 6 1 © Prentice Hall, 2002 The Physical Design Stage of SDLC (figures 2.4, 2.5 revisited) Project Identification and Selection Project Initiation.
PHP and MySQL CS How Web Site Architectures Work  User’s browser sends HTTP request.  The request may be a form where the action is to call PHP.
SQLAlchemy and Elixir (in a few minutes) Neil Blakey-Milner
SQL, Data Storage Technologies, and Web-Data Integration Week 2.
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.
Introduction to Databases Trisha Cummings. What is a database? A database is a tool for collecting and organizing information. Databases can store information.
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam P. Anthony.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 13 Designing Databases Systems Analysis and Design Kendall & Kendall Sixth Edition.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Relational Schema and SQL Queries James Wang.
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.
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
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
Working with MySQL A290/A590, Fall /07/2014.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
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.
Introduction to Databases & SQL Ahmet Sacan. What you’ll need Firefox, SQLite plugin Mirdb and Targetscan databases.
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
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
CS3220 Web and Internet Programming SQL and MySQL
CMPE/SE 131 Software Engineering March 9 Class Meeting
A Very Brief Introduction to Relational Databases
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

Complex Data Models and Relationships

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...

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

TrackLenArtistAlbumGenreRatingCount

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

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

Track Len Artist Album Genre Rating Count belongs-to

Representing Relationships in a Database

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.

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

Key Terminology Finding our way around....

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

Primary Key Rules Best practices 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 less efficient than integers User user_id password name created_at modified_at login_at

Foreign Keys A foreign key is when a table has a column that contains a key which points to the primary key of another table. When all primary keys are integers, then all foreign keys are integers - this is good - very good Artist artist_id name... Album album_ id title artist_id...

Relationship Building (in tables)

Track Len Artist Album Genre Rating Count belongs-to

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

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

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 ) ENGINE = InnoDB;

CREATE TABLE Genre ( genre_id INTEGER NOT NULL AUTO_INCREMENT KEY, name VARCHAR(255), INDEX USING BTREE (name) ) 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 ) ENGINE = InnoDB;

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); INSERT INTO Track (title, rating, len, count, album_id, genre_id) VALUES ('Stairway', 5, 482, 0, 2, 1); INSERT INTO Track (title, rating, len, count, album_id, genre_id) VALUES ('About to Rock', 5, 313, 0, 1, 2); INSERT INTO Track (title, rating, len, count, album_id, genre_id) VALUES ('Who Made Who', 5, 207, 0, 1, 2);

We have relationships! Artist Genre Album Track

Using Join Across Tables

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

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

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

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

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

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

Many-To-Many Relationships

Album belongs-to Album id title Track id title rating len count album_id Table Primary key Logical key Foreign key Track Len Rating Count Title Many One Review: One to Many ManyOne

Many One ManyOne

Many to Many Sometimes we need to model a relationship that is many-to- many We need to add a "connection" table with two foreign keys There is usually no separate primary key

Course title member-of Member user_id course_id User user_id User name Many One Many Course course_id title One Many role name

Start with a Fresh Database CREATE TABLE User ( user_id INTEGER NOT NULL AUTO_INCREMENT KEY, VARCHAR(128) UNIQUE, name VARCHAR(128) ) ENGINE=InnoDB CHARACTER SET=utf8; CREATE TABLE Course ( course_id INTEGER NOT NULL AUTO_INCREMENT KEY, title VARCHAR(128) UNIQUE ) ENGINE=InnoDB CHARACTER SET=utf8;

CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, CONSTRAINT FOREIGN KEY (user_id) REFERENCES User (user_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT FOREIGN KEY (course_id) REFERENCES Course (course_id) ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY (user_id, course_id) ) ENGINE=InnoDB CHARACTER SET=utf8; Member user_id course_id User user_id Many One Course course_id title One Many rolename

Insert Users and Courses INSERT INTO User (name, ) VALUES ('Jane', INSERT INTO User (name, ) VALUES ('Ed', INSERT INTO User (name, ) VALUES ('Sue', INSERT INTO Course (title) VALUES ('Python'); INSERT INTO Course (title) VALUES ('SQL'); INSERT INTO Course (title) VALUES ('PHP');

Insert Memberships INSERT INTO Member (user_id, course_id, role) VALUES (1, 1, 1); INSERT INTO Member (user_id, course_id, role) VALUES (2, 1, 0); INSERT INTO Member (user_id, course_id, role) VALUES (3, 1, 0); INSERT INTO Member (user_id, course_id, role) VALUES (1, 2, 0); INSERT INTO Member (user_id, course_id, role) VALUES (2, 2, 1); INSERT INTO Member (user_id, course_id, role) VALUES (2, 3, 1); INSERT INTO Member (user_id, course_id, role) VALUES (3, 3, 0);

SELECT User.name, Member.role, Course.title FROM User JOIN Member JOIN Course ON Member.user_id = User.user_id AND Member.course_id = Course.course_id ORDER BY Course.title, Member.role DESC, User.name

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