1 / 64

Chapter 1

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

strom
Download Presentation

Chapter 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 1 Getting Started with MySQL 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 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. 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. 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 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. 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. MySQL Developer's Library, Paul DuBois 4th Edition

  8. Banner Advertisement Business MySQL Developer's Library, Paul DuBois 4th Edition

  9. MySQL Developer's Library, Paul DuBois 4th Edition

  10. Mysql Installation • Please see the word document Installing MySql 5 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/ 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 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 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 MySQL Developer's Library, Paul DuBois 4th Edition

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

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

  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; MySQL Developer's Library, Paul DuBois 4th Edition

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

  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; MySQL Developer's Library, Paul DuBois 4th Edition

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

  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. 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; 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. MySQL Developer's Library, Paul DuBois 4th Edition

  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

  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. 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'); 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. 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 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; 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 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; 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 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; 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_idFROM student; MySQL Developer's Library, Paul DuBois 4th Edition

  35. Specifying Retrieval Criteria SELECT * FROM score WHERE score > 95; 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'; 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'); MySQL Developer's Library, Paul DuBois 4th Edition

  38. Arithmetic Operators + Addition - Subtraction * Multiplication / Division DIV Integer division % Modulo (remainder after division) 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 MySQL Developer's Library, Paul DuBois 4th Edition

  40. Logical Operators AND Logical AND OR Logical OR XOR Logical exclusive-OR NOT Logical negation 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 Query SELECT last_name, first_name, state FROM president WHERE state='VA' OR state='MA'; MySQL Developer's Library, Paul DuBois 4th Edition

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

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

  44. Sorting • SELECT last_name, first_name, state FROM president ORDER BY state DESC,last_nameASC; MySql Developers Library, Paul Dubois 4th Edition

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

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

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

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

  49. Concat Function • SELECT CONCAT(first_name,' ',last_name), CONCAT(city,', ',state) FROM president; MySql Developers Library, Paul Dubois 4th Edition

  50. Using Alias - As • SELECT CONCAT(first_name,' ',last_name) ASName, CONCAT(city,', ',state) AS Birthplace FROM president; MySql Developers Library, Paul Dubois 4th Edition

More Related