640 likes | 806 Views
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
E N D
Chapter 1 Getting Started with MySQL MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
Banner Advertisement Business MySQL Developer's Library, Paul DuBois 4th Edition
Mysql Installation • Please see the word document Installing MySql 5 MySQL Developer's Library, Paul DuBois 4th Edition
Sample Database • Please see appendix A for obtaining the sample database • http://www.kitebird.com/mysql-book/ MySQL Developer's Library, Paul DuBois 4th Edition
Establishing Connection • Start – All programs – mysql – mysql command line client • From command prompt : • mysql -p -u root MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
Creating a database • mysql> CREATE DATABASE sampdb; Create Database Statement + Name of the database • mysql> USE sampdb; To select a database MySQL Developer's Library, Paul DuBois 4th Edition
Create Tables CREATE TABLE president ( last_name VARCHAR(15) NOT NULL, first_nameVARCHAR(15) NOT NULL, suffix VARCHAR(5) NULL, city VARCHAR(20) NOT NULL, state VARCHAR(2) NOT NULL, birth DATE NOT NULL, death DATE NULL ); MySQL Developer's Library, Paul DuBois 4th Edition
Create tables CREATE TABLE member ( member_idINTUNSIGNED 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 ); MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
Grade Keeping Project CREATE 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; MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
Grade Keeping Project CREATE 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; MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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
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. MySQL Developer's Library, Paul DuBois 4th Edition
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'); MySQL Developer's Library, Paul DuBois 4th Edition
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. MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
Sampdb Database • You now have 6 tables in the Sampdb database and they have been populated • Member • President • Student • Grade_event • Score • Absence MySQL Developer's Library, Paul DuBois 4th Edition
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; MySQL Developer's Library, Paul DuBois 4th Edition
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_idFROM student; MySQL Developer's Library, Paul DuBois 4th Edition
Specifying Retrieval Criteria SELECT * FROM score WHERE score > 95; MySQL Developer's Library, Paul DuBois 4th Edition
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'; MySQL Developer's Library, Paul DuBois 4th Edition
Combination of Values SELECT last_name, first_name, birth, state FROM president WHERE birth < '1750-1-1' AND(state='VA' OR state='MA'); MySQL Developer's Library, Paul DuBois 4th Edition
Arithmetic Operators + Addition - Subtraction * Multiplication / Division DIV Integer division % Modulo (remainder after division) MySQL Developer's Library, Paul DuBois 4th Edition
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 MySQL Developer's Library, Paul DuBois 4th Edition
Logical Operators AND Logical AND OR Logical OR XOR Logical exclusive-OR NOT Logical negation MySQL Developer's Library, Paul DuBois 4th Edition
Logical operators SELECT last_name, first_name, state FROM president -> WHERE state='VA' AND state='MA'; Empty set (0.36 sec) • Correct Query SELECT last_name, first_name, state FROM president WHERE state='VA' OR state='MA'; MySQL Developer's 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, suffix FROM president WHERE suffix IS NOT NULL; 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_nameDESC; MySql Developers Library, Paul Dubois 4th Edition
Sorting • SELECT last_name, first_name, state FROM president ORDER BY state DESC,last_nameASC; MySql Developers Library, Paul Dubois 4th Edition
Sorting – If condition • SELECT last_name, first_name, death FROM president ORDER 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. 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 president ORDER BY birth DESC LIMIT 5; MySql Developers Library, Paul Dubois 4th Edition
Limiting Query Results • SELECT last_name, first_name, birth FROM president ORDER BY birth DESC LIMIT 10, 5; • returns 5 rows after skipping the first 10 MySql Developers Library, Paul Dubois 4th Edition
Random • SELECT last_name, first_name FROM president ORDER BY RAND() LIMIT 1; • SELECT last_name, first_name FROM president ORDER BY RAND() LIMIT 3; MySql Developers Library, Paul Dubois 4th Edition
Concat Function • SELECT CONCAT(first_name,' ',last_name), CONCAT(city,', ',state) FROM president; MySql Developers Library, Paul Dubois 4th Edition
Using Alias - As • SELECT CONCAT(first_name,' ',last_name) ASName, CONCAT(city,', ',state) AS Birthplace FROM president; MySql Developers Library, Paul Dubois 4th Edition