Architecture
Request Page
Web Browser

Web Server

Read File

Send
HTML page
Generate
HTML page

Page with
PHP
code

Pass ...
Introduction to MySQL




Relational databases
Database design
SQL




Creating databases
Creating tables
Selecting ...
Basics of Databases
A database is made up of:







fields – a compilation of types of information or properties
reco...
Relational Databases





A database may contain multiple tables too.
For example, a database used for a section
of a c...
Basics of Databases (continued)


All of this information is contained in tables
where the rows represent each record and...
Relational Databases



A database is a collection of tables
Columns define attributes of the data




All data in a c...
"Hey, a table! That's kinda like a
spreadsheet, right?"






Unlike a spreadsheet, the rows (records) of a
database mu...
Relational Databases (continued)
Student Table
•ID
•Name
•Z-account
•Rank
•Address
•Phone number

Instructor Table
•ID
•Na...
Use a Relational Database When…



You have a very large dataset
There is redundant data



Wastes disk space
Increase...
Spreadsheet Example
Title
A House for Mr. Biswas
Midnight's Children
On the Road

Author
VS Naipaul
Salman Rushdie
Jack Ke...
Spreadsheet Example
Title
A House for Mr. Biswas
Midnight's Children
On the Road

Author
VS Naipaul
Salman Rushdie
Jack Ke...
Database Design
Entity Relationship Design
Entity (“thing”, “object”)

Table

Attributes (describe entity)

Columns

Entit...
Keys




A key is a field by which records may be
sorted.
There are a number of uses for keys:






A primary key ca...
Primary Keys








Each record within a table must somehow be uniquely
identifiable.
For example, how can we make ...
Our tables
• A primary key is a unique identifier for a record in a

table.
• A foreign key in one table refers to the pri...
Simple Relational Database Example
Course Table
Department

Course

Section

Semester

Year

Instructor

CSCI

2800

001

...
Databases and the Client/Server Model







Database systems typically reside on the server, but
are not as part of t...
What is SQL?
(Adapted from material found at http://www.atlasindia.com/sql.htm)
 Dr. Edgar F. Codd created a model for da...
What is SQL? (continued)
(Adapted from material found at http://www.atlasindia.com/sql.htm)






SQL is the language u...
Different SQL Implementations






There are multiple vendors of database
products, each with their own implementation...
Using SQL




Assume that a database structure already
exists, i.e., someone has already created
tables for us containin...
Basic SQL Syntax
➔ Data Definition Language (DDL)
• CREATE TABLE / DATABASE / VIEW / etc.....
• ALTER ...
• DROP ...
➔ Dat...
Querying Records






A query is an inquiry to the database for information.
This is done with SELECT.
Syntax:
SELECT ...
Data Manipulation
There are three basic commands to
manipulate data:




INSERT
DELETE
UPDATE
Adding a Record


Syntax:
INSERT INTO tablename (fieldname [,
fieldnames]) VALUES (value [,
values])



Example:
INSERT ...
Removing a Record


Syntax:
DELETE FROM tablename WHERE
fieldname=value



Example:
DELETE FROM Customers WHERE
LastName...
Updating a Record


Syntax:
UPDATE tablename SET fieldname=value
WHERE fieldname=value



Example:
UPDATE Customers SET
...
What Is Database Normalization?






Cures the ‘SpreadSheet Syndrome’
Store only the minimal amount of
information.
R...
What are the Benefits
of Database Normalization?







Decreased storage requirements!
1 VARCHAR(20)
converted to
1...
What are the Normal Forms?







First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
Boyce-Cod...
Our Table
user

name
nickname
phone1
phone2
phone3
cell
pager
address
city
province
postal_code
country
email1
email2
web_...
First Normal Form


Remove horizontal redundancies





Each row must be unique




No two columns hold the same inf...
One Solution
user

first_name last_name phone
first_name
last_name
nickname
phone
cell
pager
address
city
province
postal_...
Satisfying 1NF
user
PK

user_id
first_name
last_name
nickname
address
city
province
postal_code
country
web_url
company
de...
Forming Relationships


Three Forms






One to One




Same Table?

One to Many




One to (zero or) One
One to...
Joining Tables
user
PK

user_id
first_name
last_name
nickname
address
city
province
postal_code
country
web_url
picture
no...
Our User Table
first_name last_name company

department

Mike

Hillyer

MySQL

Documentation

Tom

Jensen

CPNS

Finance

...
Second Normal Form



Table must be in First Normal Form
Remove vertical redundancy




Composite keys




The same ...
Satisfying 2NF

email
email
PK address
PK address
type
FK1 user_id
FK1 user_id

user
user
PK user_id
PK user_id
first_name...
Third Normal Form


Table must be in Second Normal Form






If your table is 2NF, there is a good chance it is
3NF

...
Satisfying 3NF
user_phone
user
PK

email
PK

address

FK1

user_id
format

user_id
first_name
last_name
nickname
address
c...
Finding Balance
user

user_phone

PK

user_id

FK1

first_name
last_name
nickname
unit
street_number
street_name
street_ty...
Joining Tables


Two Basic Joins





Equi-Join






Equi-Join
Outer Join (LEFT JOIN)
SELECT user.first_name, use...
De-Normalizing Tables





Use with caution
Normalize first, then de-normalize
Use only when you cannot optimize
Try t...
Upcoming SlideShare
Loading in...5
×

My sql

175

Published on

Published in: Economy & Finance, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
175
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

My sql

  1. 1. Architecture Request Page Web Browser Web Server Read File Send HTML page Generate HTML page Page with PHP code Pass PHP page and server variables (GET attributes, Server settings, etc.) PHP Interpreter Interact with Database MySQL
  2. 2. Introduction to MySQL    Relational databases Database design SQL    Creating databases Creating tables Selecting from, deleting, and updating tables  Exercises  You should have     Class notes Exercise handout MySQL Pocket Reference Useful resource: http://dev.mysql.com/doc/
  3. 3. Basics of Databases A database is made up of:     fields – a compilation of types of information or properties records – a compilation of individual items with specific values for the aforementioned information or properties For example, a student record could contain fields such as student id, name, rank, street address, city, state, and zip code. A specific record might have a student id of 12345678, name of Jane Smith, rank of sophomore, street address of 9999 Buttermilk Lane, city of Johnson City, state of Tennessee, and a zip code of 37601.
  4. 4. Relational Databases    A database may contain multiple tables too. For example, a database used for a section of a course may need to have a way to identify a student (student ID), but would not have to the student's personal information Therefore, the university's database would contain multiple tables:    Student information Course information Classroom information
  5. 5. Basics of Databases (continued)  All of this information is contained in tables where the rows represent each record and the columns represent the fields.
  6. 6. Relational Databases   A database is a collection of tables Columns define attributes of the data   All data in a column must have the same data type A record is stored in a row table name row First Name Nadia Madhu Ajuma Wade Helen Employees Last Name Li Charu Kinsaka Randal Clark Phone 2687 7856 4489 5257 2147 column
  7. 7. "Hey, a table! That's kinda like a spreadsheet, right?"    Unlike a spreadsheet, the rows (records) of a database must be independent of one another Unlike a spreadsheet, the columns (fields) of a database should be independent of one another Example: Gradebook with columns for each quiz, test, and homework grade.   Spreadsheet: one column might be used to compute the final grade Database: Cannot have a field for this. Instead, just before you presented the data (results set), you would calculate a final grade to be presented. That value is never stored in a table.
  8. 8. Relational Databases (continued) Student Table •ID •Name •Z-account •Rank •Address •Phone number Instructor Table •ID •Name •E-mail address •Department •Office location •Office phone Course Table •Course ID •Catalog description •Credit hours •List of topics Course Section Table •Course •Section number •Instructor •Students
  9. 9. Use a Relational Database When…   You have a very large dataset There is redundant data   Wastes disk space Increases errors   Security is important   Information must be updated in multiple locations Different users can be granted different permissions Strict enforcement of data types is important
  10. 10. Spreadsheet Example Title A House for Mr. Biswas Midnight's Children On the Road Author VS Naipaul Salman Rushdie Jack Kerouac Borrower Sarah Phone 646.555.1234
  11. 11. Spreadsheet Example Title A House for Mr. Biswas Midnight's Children On the Road Author VS Naipaul Salman Rushdie Jack Kerouac Borrower Sarah Phone 646.555.1234 One Flew Over the Cuckoo's Nest Sula Villette Ken Kesey Toni Morrison Charlotte Bronte Sarah 646.555.1244 Jim 646.555.4586 Data is inconsistent! Now imagine you are designing the New York Public Library database which has tens of million books and well over a million cardholders.
  12. 12. Database Design Entity Relationship Design Entity (“thing”, “object”) Table Attributes (describe entity) Columns Entity Instance Row Relationships between entities preserved in relationships between tables. If you are interested in learning more formal design methods look up “normalization” and/or “third normal form”.
  13. 13. Keys   A key is a field by which records may be sorted. There are a number of uses for keys:    A primary key can be used to uniquely identify a record. A common key is a key shared by two tables in a relational database. A foreign key is a common key that can be used to identify records from another table.
  14. 14. Primary Keys       Each record within a table must somehow be uniquely identifiable. For example, how can we make sure that we're looking at the correct student information in the student table? Answer: No two students share the same student id. Siblings may have the same parents, roommates may have the same address, but no one has identical student IDs. Therefore, we can use a field containing the student id to identify a specific record in the student database. This unique identification is called the Primary Key.
  15. 15. Our tables • A primary key is a unique identifier for a record in a table. • A foreign key in one table refers to the primary key of another.
  16. 16. Simple Relational Database Example Course Table Department Course Section Semester Year Instructor CSCI 2800 001 Spring 2006 2 CSCI 2800 201 Spring 2006 1 CSCI 2910 001 Spring 2006 4 CSCI 2910 201 Spring 2006 3 Primary keys Instructor Table ID Name E-mail Phone 1 Bailes bailes@etsu.edu 423.439.6958 2 Bailey baileyg@etsu.edu 423.439.6959 3 Laws lawsm@etsu.edu 423.439.6952 4 Tarnoff tarnoff@etsu.edu 423.439.6404
  17. 17. Databases and the Client/Server Model     Database systems typically reside on the server, but are not as part of the software providing server functionality. An interface must exist between server software and the database. Three tier architecture – Server/client model adds middle layer that handles transactions between client and database server. Middle layer provides:     ability to access more than one database with a single transaction ability connect to many different types of data sources ability to prioritize requests before they reach the data base improved security
  18. 18. What is SQL? (Adapted from material found at http://www.atlasindia.com/sql.htm)  Dr. Edgar F. Codd created a model for data   storage that used a simple programming language to access the stored data In 1971, IBM used Dr. Codd's work to created a simple non-procedural language called Structured English Query Language (SEQUEL) In the late 80's, two standardization organizations (ANSI and ISO) developed a standardized version called Structured Query Language or SQL.
  19. 19. What is SQL? (continued) (Adapted from material found at http://www.atlasindia.com/sql.htm)    SQL is the language used to query all databases. It is a generic way to access the information in a database. Understanding SQL is vital to creating a database application such as a web interface. Web Application SQL Database
  20. 20. Different SQL Implementations    There are multiple vendors of database products, each with their own implementation of SQL Each product should be compliant with ANSI standard Added features or commands do exists. These are called extensions.
  21. 21. Using SQL   Assume that a database structure already exists, i.e., someone has already created tables for us containing fields and records. What sort of things might we want to do to this database?      Start/end a session with a specific database Read a record Insert a new record Delete an existing record Edit and restore an existing record
  22. 22. Basic SQL Syntax ➔ Data Definition Language (DDL) • CREATE TABLE / DATABASE / VIEW / etc..... • ALTER ... • DROP ... ➔ Data Manipulation Language (DML) • • • • SELECT ... FROM / INTO … WHERE ... INSERT INTO ... VALUES ... UPDATE … SET … WHERE ... DELETE FROM … WHERE ...
  23. 23. Querying Records    A query is an inquiry to the database for information. This is done with SELECT. Syntax: SELECT *| fieldname [, fieldnames] FROM tablename [, tablenames] WHERE fieldname=value ORDER BY fieldname [, fieldnames] Example: SELECT FirstName FROM Customers WHERE LastName='Smith'
  24. 24. Data Manipulation There are three basic commands to manipulate data:    INSERT DELETE UPDATE
  25. 25. Adding a Record  Syntax: INSERT INTO tablename (fieldname [, fieldnames]) VALUES (value [, values])  Example: INSERT INTO Customers (FirstName, LastName) VALUES ('Jane','Smith')
  26. 26. Removing a Record  Syntax: DELETE FROM tablename WHERE fieldname=value  Example: DELETE FROM Customers WHERE LastName='Jones'
  27. 27. Updating a Record  Syntax: UPDATE tablename SET fieldname=value WHERE fieldname=value  Example: UPDATE Customers SET FirstName='Jeff' WHERE LastName='Smith'
  28. 28. What Is Database Normalization?     Cures the ‘SpreadSheet Syndrome’ Store only the minimal amount of information. Remove redundancies. Restructure data.
  29. 29. What are the Benefits of Database Normalization?       Decreased storage requirements! 1 VARCHAR(20) converted to 1 TINYINT UNSIGNED in a table of 1 million rows is a savings of ~20 MB Faster search performance!    Smaller file for table scans. More directed searching. Improved data integrity!
  30. 30. What are the Normal Forms?       First Normal Form (1NF) Second Normal Form (2NF) Third Normal Form (3NF) Boyce-Codd Normal Form (BCNF) Fourth Normal Form (4NF) Fifth Normal Form (5NF)
  31. 31. Our Table user name nickname phone1 phone2 phone3 cell pager address city province postal_code country email1 email2 web_url company department picture notes email_format name phone1 phone2 email1 email2 Mike Hillyer 403-5551717 403-5551919 mike@hoppen.c om mhillyer@mysite. com Tom Jensen 403-5551919 403-5551313 tom@openwin.o rg tom@supersite.o rg Ray Smith 403-5551919 403-5551111 ray@cpma.com
  32. 32. First Normal Form  Remove horizontal redundancies    Each row must be unique   No two columns hold the same information No single column holds more than a single item Use a primary key Benefits    Easier to query/sort the data More scalable Each row can be identified for updating
  33. 33. One Solution user first_name last_name phone first_name last_name nickname phone cell pager address city province postal_code country web_url department picture notes email Mike Hillyer 403-555-1717 mike@hoppen.com Mike Hillyer 403-555-1919 mhillyer@mysite.com Tom Jensen 403-555-1919 tom@openwin.org Tom Jensen 403-555-1313 tom@supersite.org Ray Smith 403-555-1919 ray@cpma.com Ray Smith 403-555-1111 • • • Multiple rows per user Emails are associated with only one other phone Hard to Search
  34. 34. Satisfying 1NF user PK user_id first_name last_name nickname address city province postal_code country web_url company department picture notes email PK email_id address phone PK phone_id country_code number extension
  35. 35. Forming Relationships  Three Forms     One to One   Same Table? One to Many   One to (zero or) One One to (zero or) Many Many to Many Place PK of the One in the Many Many to Many  Create a joining table
  36. 36. Joining Tables user PK user_id first_name last_name nickname address city province postal_code country web_url picture notes email_format phone user_phone PK,FK1 phone_id PK user_id type email PK address FK1 user_id PK phone_id country_code number extension
  37. 37. Our User Table first_name last_name company department Mike Hillyer MySQL Documentation Tom Jensen CPNS Finance Ray Smith CPNS Documentation user PK user_id first_name last_name nickname address city province postal_code country web_url picture notes email_format phone user_phone PK,FK1 phone_id PK user_id type email PK address FK1 user_id PK phone_id country_code number extension
  38. 38. Second Normal Form   Table must be in First Normal Form Remove vertical redundancy   Composite keys   The same value should not repeat across rows All columns in a row must refer to BOTH parts of the key Benefits   Increased storage efficiency Less data repetition
  39. 39. Satisfying 2NF email email PK address PK address type FK1 user_id FK1 user_id user user PK user_id PK user_id first_name last_name first_name nickname last_name address nickname city address province city postal_code province country postal_code web_url country picture web_url notes picture email_format notes phone user_phone PK,FK1 user_id PK,FK2 phone_id PK phone_id country_code number extension type user_company PK,FK1 user_id PK,FK2 company_id department company PK company_id name
  40. 40. Third Normal Form  Table must be in Second Normal Form    If your table is 2NF, there is a good chance it is 3NF All columns must relate directly to the primary key Benefits  No extraneous data
  41. 41. Satisfying 3NF user_phone user PK email PK address FK1 user_id format user_id first_name last_name nickname address city province postal_code country web_url picture notes PK,FK1 PK,FK2 user_id phone_id phone PK phone_id country_code number type extension user_company PK,FK1 PK,FK2 user_id company_id department company PK company_id name
  42. 42. Finding Balance user user_phone PK user_id FK1 first_name last_name nickname unit street_number street_name street_type quadrant web_url picture notes postal_code PK,FK1 user_id PK,FK2 phone_id extension email PK user_id format PK phone_id FK1 type_id area_code NXX NCX country_id FK2 country type PK type_id PK country_id Name phone_code type address FK1 phone user_department PK,FK1 PK,FK2 user_id department_id department PK postal_code FK1 city city_id PK city_id FK1 department_id FK1 postal_code PK name company_id province name province_id PK province_id FK1 Name Abbreviation country_id company PK company_id name
  43. 43. Joining Tables  Two Basic Joins    Equi-Join     Equi-Join Outer Join (LEFT JOIN) SELECT user.first_name, user.last_name, email.address FROM user, email WHERE user.user_id = email.user_id LEFT JOIN    SELECT user.first_name, user.last_name, email.address FROM user LEFT JOIN email ON user.user_id = email.user_id
  44. 44. De-Normalizing Tables     Use with caution Normalize first, then de-normalize Use only when you cannot optimize Try temp tables, UNIONs, VIEWs, subselects first
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×