64
Chapter 1 Getting Started with MySQL 1 MySQL Developer's Library, Paul DuBois 4th Edition

Chapter 1

  • Upload
    strom

  • View
    32

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 1. Getting Started with MySQL. Why a database system?. information you want to organize and manage is so voluminous or complex that your records. large corporations processing millions of transactions a day - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 1

1

Chapter 1

Getting Started with MySQL

MySQL Developer's Library, Paul DuBois 4th Edition

Page 2: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

2

Why a database system?

• information you want to organize and manage is so voluminous or complex that your records.

• large corporations processing millions of transactions a day

• But even small-scale operations involving a single person maintaining information

Page 3: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

3

Database system - Scenarios

• Your carpentry business has several employees. You need to maintain employee and payroll records so that you know who you've paid and when, and you must summarize those records so that you can report earnings statements to the government for tax purposes. You also need to keep track of the jobs your company has been hired to do and which employees you've scheduled to work on each job.

Page 4: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

4

Database system - Scenarios

• You're a teacher who needs to keep track of grades and attendance. Each time you give a quiz or a test, you record every student's grade. It's easy enough to write down scores in a gradebook, but using the scores later is a tedious chore. You'd rather avoid sorting the scores for each test to determine the grading curve, and you'd really rather not add up each student's scores when you determine final grades at the end of the grading period. Counting each student's absences is no fun, either.

Page 5: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

5

Advantages of Electronically Maintained records

• Reduced record filing time• Reduced record retrieval time• Flexible retrieval order• Flexible output format• Simultaneous multiple-user access to records• Remote access to and electronic transmission

of records

Page 6: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

6

Sample Databases

• The organizational secretary scenario. Our organization has these characteristics: It's composed of people drawn together through an affinity for United States history (called, for lack of a better name, the U.S. Historical League). The members renew their membership periodically on a dues-paying basis. Dues go toward League expenses such as publication of a newsletter, "Chronicles of U.S. Past." The League also operates a small Web site; it hasn't been developed very much, but you'd like to change that.

Page 7: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

7

Sample Databases

• The grade-keeping scenario. You are a teacher who administers quizzes and tests during the grading period, records scores, and assigns grades. Afterward, you determine final grades, which you turn in to the school office along with an attendance summary.

Page 8: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

8

Banner Advertisement BusinessCompany TableCompany NameCpmpany_Num (PK)AddressPhone

Ad Table

Company_num (FK)

Ad_num (FK)

Hit Fee

Hit_table

Ad_num (FK)

date

Page 9: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

9

Page 10: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

10

Mysql Installation

• Please see the word document Installing MySql 5

Page 11: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

11

Sample Database

• Please see appendix A for obtaining the sample database

• http://www.kitebird.com/mysql-book/

Page 12: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

12

Establishing Connection

• Start – All programs – mysql – mysql command line client

• From command prompt : – mysql -p -u root

Page 13: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

13

Executing MySql statements

• In the mysql command Line Client• Terminate all mysql statements with a ;– mysql> SELECT NOW(); – mysql> SELECT NOW(),

-> USER(), -> VERSION() -> ;

mysql waits for the statement terminator, you need not enter a statement all on a single line. You can spread it over several lines if you want

Page 14: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

14

Creating a database

• mysql> CREATE DATABASE sampdb; Create Database Statement + Name of the database

• mysql> USE sampdb; To select a database

Page 15: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

15

Create Tables

CREATE TABLE president (

last_name VARCHAR(15) NOT NULL, first_name VARCHAR(15) NOT NULL, suffix VARCHAR(5) NULL, city VARCHAR(20) NOT NULL, state VARCHAR(2) NOT NULL, birth DATE NOT NULL, death DATE NULL );

Page 16: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

16

Create tablesCREATE TABLE member (

member_id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (member_id), last_name VARCHAR(20) NOT NULL, first_name VARCHAR(20) NOT NULL, suffix VARCHAR(5) NULL, expiration DATE NULL, email VARCHAR(100) NULL, street VARCHAR(50) NULL, city VARCHAR(50) NULL, state VARCHAR(2) NULL, zip VARCHAR(10) NULL, phone VARCHAR(20) NULL, interests VARCHAR(255) NULL

);

Page 17: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

17

Check structure of the table

• mysql> DESCRIBE president; • SHOW COLUMNS FROM president;• To view tables in the database– SHOW TABLES;

• To view databases on the server– Show databases;

Page 18: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

18

Grade Keeping ProjectCREATE TABLE students ( name VARCHAR(20) NOT NULL, sex ENUM('F','M') NOT NULL, student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,

PRIMARY KEY (student_id) ) ENGINE = InnoDB;

Page 19: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

19

Grade Keeping Project

CREATE TABLE grade_event ( date DATE NOT NULL, category ENUM('T','Q') NOT NULL, event_id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (event_id) ) ENGINE = InnoDB;

Page 20: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

20

Grade Keeping ProjectCREATE TABLE score ( student_id INT UNSIGNED NOT NULL, event_id INT UNSIGNED NOT NULL, score INT NOT NULL, PRIMARY KEY (event_id, student_id), INDEX (student_id), FOREIGN KEY (event_id) REFERENCES grade_event (event_id), FOREIGN KEY (student_id) REFERENCES students (student_id) ) ENGINE = InnoDB;

Page 21: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

21

Score table

• combination of the two columns a PRIMARY KEY ensures that we won't have duplicate scores for a student for a given quiz or test.

• combination of event_id and student_id that is unique.

• Foreign Key constraints - each student_id value in the score table must match some student_id value in the student table.

Page 22: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

22

Grade Keeping Project

CREATE TABLE absence ( student_id INT UNSIGNED NOT NULL, date DATE NOT NULL, PRIMARY KEY (student_id, date), FOREIGN KEY (student_id) REFERENCES students

(student_id) ) ENGINE = InnoDB;

Page 23: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

23

Storage Engine in Mysql• Default storage engine is MyISAM (indexed sequential access

method)• InnoDB offers "referential integrity" through the use of foreign

keys. • MySQL to enforce certain constraints on the interrelationships

between tables - important for the grade-keeping project tables:– Score rows are tied to grade events and to students: don't allow

entry of rows into the score table unless the student ID and grade event ID are known in the student and grade_event tables.

– Absence rows are tied to students: don't allow entry of rows into the absence table unless the student ID is known in the student table.

Page 24: Chapter 1

24

INSERT data in the Tables• INSERT INTO tbl_name VALUES(value1,value2,...);

Example:• INSERT INTO students VALUES('Kyle','M',NULL);• INSERT INTO grade_event VALUES('2008-09-

03','Q',NULL); • the VALUES list must contain a value for each

column in the table, in the order that the columns are stored in the table.

• NULL values are for the AUTO_INCREMENT columns in the student and grade_event tables.

MySQL Developer's Library, Paul DuBois 4th Edition

Page 25: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

25

INSERT data• insert several rows into a table with a single

INSERT statement by specifying multiple value lists:

• INSERT INTO tbl_name VALUES(...),(...),... ; Example:

• INSERT INTO students VALUES('Avery','F',NULL),('Nathan','M',NULL);

• Less typing than multiple INSERT statements, and more efficient for the server to execute.

Page 26: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

26

INSERT data• name the columns to which you want to assign

values, and then list the values• INSERT INTO member (last_name,first_name)

VALUES('Stein','Waldo'); • INSERT INTO students (name,sex)

VALUES('Abby','F'),('Joseph','M');

Page 27: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

27

Foreign Key Constraints with INSERT Data

• INSERT INTO score (event_id,student_id,score) VALUES(9999,9999,0);

• ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`sampdb`.`score`, CONSTRAINT `score_ibfk_1` FOREIGN KEY (`event_id`) REFERENCES `grade_event` (`event_id`))

• foreign key relationships prevent entry of bad rows in the score table.

Page 28: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

28

Adding data from a file

• Unzip the sample database• Copy and paste the following files in the data

directory – location may vary! C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.1\

data\sampdb- president.txt- Student.txt- Member.txt- Score.txt- Absence.txt

Page 29: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

29

Adding data from a file

• mysql> source insert_president.sql; • Before running the below command– TRUNCATE TABLE member;

delete all data in the table

• LOAD DATA INFILE “member.txt” INTO TABLE member;

• LOAD DATA INFILE “president.txt” INTO TABLE president;

Page 30: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

30

Adding data from file

• Copy and paste the data from “insert_student” in Mysql command prompt to populate the student table– Insert_student file is in the unzipped sampdb

folder • Copy and paste the data from

“insert_grade_event” in Mysql command prompt to populate the grade_event table

Page 31: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

31

Adding data from file

• Copy and paste the data from “insert_score” in Mysql command prompt to populate the score table

• LOAD DATA INFILE “absence.txt” INTO TABLE absence;

Page 32: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

32

Sampdb Database

• You now have 6 tables in the Sampdb database and they have been populated

- Member- President- Student- Grade_event- Score- Absence

Page 33: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

33

Query

• To retrieve data from the database• SELECT * FROM president; – All data in the table president

• syntax of the SELECT statement is:SELECT what to retrieve FROM table or tables WHERE conditions that data must satisfy;

Page 34: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

34

Query

SELECT birth FROM president WHERE last_name = 'Eisenhower';

Retrieve data from one column SELECT name FROM student;

Data from 2 columns SELECT name, sex, student_id FROM student;

Page 35: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

35

Specifying Retrieval Criteria

SELECT * FROM score WHERE score > 95;

Page 36: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

36

string values

SELECT last_name, first_name FROM president WHERE last_name='ROOSEVELT';

SELECT last_name, first_name, birth FROM president

WHERE birth < '1750-1-1';

Page 37: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

37

Combination of Values

SELECT last_name, first_name, birth, state FROM president

WHERE birth < '1750-1-1' AND (state='VA' OR state='MA');

Page 38: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

38

Arithmetic Operators

+ Addition - Subtraction * Multiplication / Division DIV Integer division % Modulo (remainder after division)

Page 39: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

39

Comparison Operators

< Less than <= Less than or equal to = Equal to <=> Equal to (works even for NULL values) >or != Not equal to >= Greater than or equal to > Greater than

Page 40: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

40

Logical Operators

AND Logical AND OR Logical OR XOR Logical exclusive-OR NOT Logical negation

Page 41: Chapter 1

MySQL Developer's Library, Paul DuBois 4th Edition

41

Logical operators

SELECT last_name, first_name, state FROM president ->

WHERE state='VA' AND state='MA'; Empty set (0.36 sec)• Correct QuerySELECT last_name, first_name, state FROM

president WHERE state='VA' OR state='MA';

Page 42: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Null and Not Null Queries

• SELECT last_name, first_name FROM president WHERE death IS NULL;

• SELECT last_name, first_name, suffixFROM president WHERE suffix IS NOT NULL;

Page 43: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Sorting Queries

• SELECT last_name, first_name FROM president ORDER BY last_name;

• SELECT last_name, first_name FROM president ORDER BY last_name DESC;

Page 44: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Sorting

• SELECT last_name, first_name, state FROM presidentORDER BY state DESC, last_name ASC;

Page 45: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Sorting – If condition

• SELECT last_name, first_name, death FROM presidentORDER BY IF(death IS NULL,0,1), death DESC;

• IF() evaluates to 0 for NULL values and 1 for non-NULL values.

• This places all NULL values ahead of all non-NULL values.

Page 46: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Limiting Query Results

• SELECT last_name, first_name, birth FROM president ORDER BY birth LIMIT 5;

• SELECT last_name, first_name, birth FROM presidentORDER BY birth DESC LIMIT 5;

Page 47: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Limiting Query Results

• SELECT last_name, first_name, birth FROM presidentORDER BY birth DESC LIMIT 10, 5;

• returns 5 rows after skipping the first 10

Page 48: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Random

• SELECT last_name, first_name FROM presidentORDER BY RAND() LIMIT 1;

• SELECT last_name, first_name FROM president ORDER BY RAND() LIMIT 3;

Page 49: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Concat Function

• SELECT CONCAT(first_name,' ',last_name),CONCAT(city,', ',state)FROM president;

Page 50: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Using Alias - As

• SELECT CONCAT(first_name,' ',last_name) AS Name, CONCAT(city,', ',state) AS BirthplaceFROM president;

Page 51: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Dates

• SELECT * FROM grade_event WHERE date = '2008-10-01';

• SELECT last_name, first_name, death FROM president WHERE death>='1970-01-01' AND death<'1980-01-01';

Page 52: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Functions Year(), Month(), dayofmonth()

• SELECT last_name, first_name, birthFROM president WHERE MONTH(birth) = 3;

• SELECT last_name, first_name, birthFROM presidentWHERE MONTHNAME(birth) = 'March';

Page 53: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Functions Year(), Month(), dayofmonth()

SELECT last_name, first_name, birthFROM president WHERE MONTH(birth) = 3 AND DAYOFMONTH(birth) = 29;

Page 54: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Date Calculations

• SELECT last_name, first_name, birth, death,TIMESTAMPDIFF(YEAR, birth, death) AS age FROM president WHERE death IS NOT NULL ORDER BY age DESC LIMIT 5;

Page 55: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Date Calculations – Add date

• SELECT DATE_ADD('1970-1-1', INTERVAL 10 YEAR);

• SELECT last_name, first_name, deathFROM president WHERE death>=“1970-1-1”AND death < DATE_ADD(“1970-1-1”, INTERVAL 10

YEAR);

Page 56: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Pattern matching

• SELECT last_name, first_name FROM president WHERE last_name LIKE 'W%';

Page 57: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

summaries

• SELECT DISTINCT state FROM president ORDER BY state;

• Use the DISTINCT keyword to remove duplicate rows from a result.

Page 58: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

summaries

• SELECT COUNT(*) FROM member; • COUNT(*) tells you the number of rows in

your table.• SELECT COUNT(*) FROM grade_event WHERE

category = 'Q';

Page 59: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

summaries

• SELECT sex, COUNT(*) FROM student GROUP BY sex;

• SELECT state, COUNT(*) AS count FROM presidentGROUP BY state ORDER BY count DESC;

Page 60: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Queries – Multiple Tables

• SELECT student_id, date, score, category FROM grade_event INNER JOIN score ON grade_event.event_id = score.event_idWHERE date = '2008-09-23';

Page 61: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Queries – Multiple Tables

• SELECT student.name, grade_event.date, score.score, grade_event.category FROM grade_event INNER JOIN score INNER JOIN student ON grade_event.event_id = score.event_id AND score.student_id = student.student_idWHERE grade_event.date = '2008-09-23';

Page 62: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Queries – Multiple Tables and Functions

• SELECT grade_event.date, student.sex, COUNT(score.score) AS count, AVG(score.score) AS averageFROM grade_event INNER JOIN score INNER JOIN studentON grade_event.event_id = score.event_id AND score.student_id = student.student_id GROUP BY grade_event.date, student.sex;

Page 63: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Subquery

• SELECT last_name, first_name, birth FROM presidentWHERE birth < (SELECT birth FROM presidentWHERE last_name = 'Jackson' AND first_name = 'Andrew');

Page 64: Chapter 1

MySql Developers Library, Paul Dubois 4th Edition

Delete Data

• DELETE FROM tbl_name WHERE which rows to delete;