64
MySQL Database System MySQL Database System Hiep Dinh Hiep Dinh CS 157B-Section 2 CS 157B-Section 2

MySQL Database System Hiep Dinh

Embed Size (px)

Citation preview

Page 1: MySQL Database System Hiep Dinh

MySQL Database SystemMySQL Database System

Hiep DinhHiep DinhCS 157B-Section 2CS 157B-Section 2

Page 2: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 22

2-Tier Architecture2-Tier Architecture

WebBrowser(Client)

WebServer

PHP

Page 3: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 33

3-Tier Architecture3-Tier Architecture

WebBrowser(Client)

DatabaseServer

WebServer PHP

Page 4: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 44

Installation SummaryInstallation Summary

• More detailed installation instructions are More detailed installation instructions are given on the CDgiven on the CD

• Install MySQL in Install MySQL in c:\mysqlc:\mysql

• MySQL can be installed as a serviceMySQL can be installed as a service(Win 2000/XP)(Win 2000/XP)

• Can make icons on the desktop for Can make icons on the desktop for starting and stopping the server.starting and stopping the server.

Page 5: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 55

Command Line ClientCommand Line Client

• The standard command line client isThe standard command line client is•c:\mysql\bin\mysql.exec:\mysql\bin\mysql.exe

• The command line client can be used to The command line client can be used to send commands and SQL queries to the send commands and SQL queries to the MySQL serverMySQL server

• There are also GUI clients such as MyCCThere are also GUI clients such as MyCC

Page 6: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 66

Client-Server InteractionClient-Server Interaction

MySQLServer

ClientProgram

Make a request(SQL query)

Get results

Client program can be a MySQL command line client,GUI client, or a program written in any language suchas C, Perl, PHP, Java that has an interface to theMySQL server.

Page 7: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 77

Connecting to the ServerConnecting to the Server

• Use a command prompt that sets the path Use a command prompt that sets the path to to c:\mysql\binc:\mysql\bin

• The following command connects to the The following command connects to the server:server:– mysql -u root -pmysql -u root -p

– you are prompted for the root password.you are prompted for the root password.– you can now send comands and SQL you can now send comands and SQL

statements to the serverstatements to the server

Page 8: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 88

WARNING WARNINGWARNING WARNING

•WARNINGWARNING• Always assume that everything is case Always assume that everything is case

sensitive, especially table names.sensitive, especially table names.

• This is not the case in Windows XP but it This is not the case in Windows XP but it is the case in Linuxis the case in Linux

Page 9: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 99

Entering commands (1)Entering commands (1)

• Show all the databasesShow all the databases– SHOW DATABASES;SHOW DATABASES;

mysql> SHOW DATABASES;+-------------+| Database |+-------------+| bookstore || employee_db || mysql || student_db || test || web_db |+-------------+

Page 10: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1010

Entering commands (2)Entering commands (2)• Choosing a database and showing its tablesChoosing a database and showing its tables

– USE test;USE test;SHOW tables;SHOW tables;

mysql> USE test;Database changedmysql> SHOW tables;+----------------+| Tables_in_test |+----------------+| books || name2 || names || test |+----------------+4 rows in set (0.00 sec)mysql>

Page 11: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1111

Entering commands (3)Entering commands (3)• Show the structure of a tableShow the structure of a table

– DESCRIBE names;DESCRIBE names;

mysql> DESCRIBE names;+-----------+-------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-----------+-------------+------+-----+---------+----------------+| id | int(11) | | PRI | NULL | auto_increment || firstName | varchar(20) | | | | || lastName | varchar(20) | | | | |+-----------+-------------+------+-----+---------+----------------+3 rows in set (0.00 sec)

mysql>

Page 12: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1212

Entering commands (4)Entering commands (4)• Show the rows of a table (all columns)Show the rows of a table (all columns)

– SELECT * FROM names;SELECT * FROM names;

mysql> SELECT * FROM names;+----+-----------+------------+| id | firstName | lastName |+----+-----------+------------+| 1 | Fred | Flintstone || 2 | Barney | Rubble |+----+-----------+------------+2 rows in set (0.00 sec)

mysql>

Page 13: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1313

Entering commands (5)Entering commands (5)• Inserting a new recordInserting a new record

– INSERT INTO names (firstName,INSERT INTO names (firstName,lastName) VALUES ('Rock','Quarry');lastName) VALUES ('Rock','Quarry');

– SELECT * FROM names;SELECT * FROM names;

mysql> INSERT INTO names (firstName, lastName) VALUES ('Ralph', 'Quarry');Query OK, 1 row affected (0.02 sec)mysql> SELECT * FROM names;+----+-----------+------------+| id | firstName | lastName |+----+-----------+------------+| 1 | Fred | Flintstone || 2 | Barney | Rubble || 3 | Ralph | Quarry |+----+-----------+------------+3 rows in set (0.00 sec)mysql>

Page 14: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1414

Entering commands (6)Entering commands (6)• Updating a recordUpdating a record

– UPDATE names SET lastName = 'Stone'UPDATE names SET lastName = 'Stone'WHERE id=3;WHERE id=3;

– SELECT * FROM names;SELECT * FROM names;

mysql> UPDATE names SET lastName = 'Stone' WHERE id=3;Query OK, 1 row affected (0.28 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> SELECT * FROM names;+----+-----------+------------+| id | firstName | lastName |+----+-----------+------------+| 1 | Fred | Flintstone || 2 | Barney | Rubble || 3 | Ralph | Stone |+----+-----------+------------+3 rows in set (0.00 sec)mysql>

Page 15: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1515

Logging outputLogging output

• The commands you type and their ouput The commands you type and their ouput can be logged to a file by using the can be logged to a file by using the following command inside the MySQL following command inside the MySQL command line clientcommand line client

•tee log.txttee log.txt

• Here log.txt is the name of the file Here log.txt is the name of the file

Page 16: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1616

Executing SQL files (1)Executing SQL files (1)

• It is usually better to use an editor to write an SQL script It is usually better to use an editor to write an SQL script and send it to the server.and send it to the server.

• A file of SQL commands such as A file of SQL commands such as books.sqlbooks.sql can be can be executed by the server by using a command such asexecuted by the server by using a command such as– C:\mysql\bin\mysql -u root -p < C:\mysql\bin\mysql -u root -p < books.sqlbooks.sql

• This assumes that This assumes that books.sqlbooks.sql is in your current is in your current directory. Otherwise the complete path to directory. Otherwise the complete path to books.sqlbooks.sql must be suppliedmust be supplied

Page 17: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1717

Executing SQL files (2)Executing SQL files (2)

• A file of SQL commands such as A file of SQL commands such as books.sqlbooks.sql can also be executed from can also be executed from inside the MySQL client using the inside the MySQL client using the sourcesource commandcommand– source c:\.....\books.sqlsource c:\.....\books.sql

• Here the full path to Here the full path to books.sqlbooks.sql should should be used.be used.

Page 18: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1818

DocumentationDocumentation

• MySQL comes with a tutorial and complete MySQL comes with a tutorial and complete documentation in a HUGE file:documentation in a HUGE file:– c:\mysql\Docs\manual.htmlc:\mysql\Docs\manual.html

• Table of contents with links:Table of contents with links:– c:\mysql\Docs\manual_toc.htmlc:\mysql\Docs\manual_toc.html

• Use this file to locate the link to the topic Use this file to locate the link to the topic you are interested in.you are interested in.

Page 19: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 1919

Database concepts (1)Database concepts (1)

• A relational database management system A relational database management system consists of a number of databases.consists of a number of databases.

• Each database consists of a number of tables.Each database consists of a number of tables.

• Example tableExample table

isbn title author pub year price

bookstable rows

(records)

columnheadings

Page 20: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2020

Some SQL data types (1)Some SQL data types (1)

• Each entry in a row has a type specified Each entry in a row has a type specified by the column.by the column.

• Numeric data typesNumeric data types– TINYINT, SMALLINT, MEDIUMINT,TINYINT, SMALLINT, MEDIUMINT,

– INT, BIGINTINT, BIGINT

– FLOAT(display_length, decimals)FLOAT(display_length, decimals)

– DOUBLE(display_length, decimals)DOUBLE(display_length, decimals)

– DECIMAL(display_length, decimals)DECIMAL(display_length, decimals)•NUMERICNUMERIC is the same as is the same as DECIMALDECIMAL

Page 21: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2121

Some SQL data types (2)Some SQL data types (2)

• Date and time typesDate and time types– DATEDATE

• format is YYYY-MM-DDformat is YYYY-MM-DD

– DATETIMEDATETIME• format YYYY-MM-DD HH:MM:SSformat YYYY-MM-DD HH:MM:SS

– TIMESTAMPTIMESTAMP• format YYYYMMDDHHMMSSformat YYYYMMDDHHMMSS

– TIMETIME• format HH:MM:SSformat HH:MM:SS

– YEARYEAR• default length is 4default length is 4

Page 22: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2222

SQL data types (3)SQL data types (3)

• String typesString types– CHARCHAR

• fixed length string, e.g., fixed length string, e.g., CHAR(20)CHAR(20)

– VARCHARVARCHAR

• variable length string, e.g., VARCHAR(20)variable length string, e.g., VARCHAR(20)

– BLOB, TINYBLOB, MEDIUMBLOB, BLOB, TINYBLOB, MEDIUMBLOB, LONGBLOBLONGBLOB

• same as same as TEXTTEXT, , TINYTEXTTINYTEXT ... ...

– ENUMENUM

• list of items from which value is selectedlist of items from which value is selected

Page 23: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2323

SQL commands SHOW, USESQL commands SHOW, USE• SHOWSHOW

– Display databases or tables in current Display databases or tables in current database;database;

– Example (command line client):Example (command line client):– show databases;show databases;

– show tables;show tables;

• USEUSE

– Specify which database to useSpecify which database to use– ExampleExample– use bookstore;use bookstore;

Page 24: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2424

The The CREATECREATE Command (1) Command (1)

•CREATE CREATE creates a creates a databasedatabase table table

CREATE TABLE table_name( column_name1 column_type1, column_name2 column_type2, ... column_nameN column_typeN);

Note: To create a database use the statementCREATE db_name;

Page 25: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2525

The CREATE Command (2)The CREATE Command (2)

• Specifying primary keysSpecifying primary keysCREATE TABLE table_name( column_name1 column_type1 NOT NULL DEFAULT '0', column_name2 column_type2, ... column_nameN column_typeN, PRIMARY KEY (column_name1));

Page 26: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2626

The CREATE Command (3)The CREATE Command (3)

• autoincrement primary integer keysautoincrement primary integer keys

CREATE TABLE table_name( column_name1 column_type1 PRIMARY KEY NOT NULL DEFAULT '0' AUTO_INCREMENT, column_name2 column_type2, ... column_nameN column_typeN,);

Page 27: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2727

The CREATE Command (4)The CREATE Command (4)

• Can also create UNIQUE keys. They are Can also create UNIQUE keys. They are similar to PRIMARY KEYS but can have similar to PRIMARY KEYS but can have NULL values.NULL values.

• Can also create INDEX fields.Can also create INDEX fields.

Page 28: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2828

Conditional CreationConditional Creation

• Conditional database creationConditional database creation– CREATE DATABASE IF NOT EXISTS CREATE DATABASE IF NOT EXISTS db_name;db_name;

• Conditional table creationConditional table creation– CREATE TABLE IF NOT EXISTS CREATE TABLE IF NOT EXISTS table_name;table_name;

Page 29: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 2929

The DROP CommandThe DROP Command

• To delete databases and tables use the To delete databases and tables use the DROP commandDROP command

• ExamplesExamples– DROP DATABASE db_name;DROP DATABASE db_name;– DROP DATABASE IF EXISTS db_name;DROP DATABASE IF EXISTS db_name;– DROP TABLE table_name;DROP TABLE table_name;– DROP TABLE IF EXISTS table_name;DROP TABLE IF EXISTS table_name;

Note: Don't confuse DROP with DELETE which deletes rowsof a table.

Page 30: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3030

The INSERT CommandThe INSERT Command

• Inserting rows into a tableInserting rows into a tableINSERT INTO table_name ( col_1, col_2, ..., col_N)VALUES ( val_1, val_2, ..., val_N);

String values are enclosed in single quotes by defaultbut double quotes are also allowed. Literal quotesneed to be escaped using \' and \"

Page 31: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3131

The SELECT Command (1)The SELECT Command (1)

• Selecting rows from a tableSelecting rows from a table

• Simplest form: select all columnsSimplest form: select all columns

• Select specified columnsSelect specified columns

• Conditional selection of rowsConditional selection of rowsSELECT column_list FROM table_name;

SELECT * FROM table_name;

SELECT column_list FROM table_nameWHERE condition;

Page 32: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3232

The SELECT Command (2)The SELECT Command (2)

• Specifying ascending row orderingSpecifying ascending row ordering

• Specifying descending row orderingSpecifying descending row ordering

SELECT column_list FROM table_nameWHERE conditionORDER by ASC;

SELECT column_list FROM table_nameWHERE conditionORDER by DESC;

Page 33: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3333

The SELECT Command (3)The SELECT Command (3)

• There are many other variations of the There are many other variations of the select command.select command.

• Example: finding the number of records in Example: finding the number of records in a table assuming a primary key called a table assuming a primary key called idid::

• Can also perform searching using the Can also perform searching using the WHERE optionWHERE option

SELECT COUNT(id) FROM table_name

Page 34: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3434

The UPDATE CommandThe UPDATE Command• Used to modify an existing recordUsed to modify an existing record

• Conditional update versionConditional update version

UPDATE table_nameSET col_1 = 'new_value1',..., col_n = 'new_value2';

UPDATE table_nameSET col_1 = 'new_value1',..., col_n = 'new_value2'WHERE condition;

Page 35: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3535

marks.sql (1)marks.sql (1)studentID first_name

USE test;CREATE TABLE marks ( studentID SMALLINT AUTO_INCREMENT NOT NULL, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, mark SMALLINT DEFAULT 0 NOT NULL, PRIMARY KEY (studentID));

markstable

last_name mark

Page 36: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3636

marks.sql (2) marks.sql (2) -- Insert some rows into marks table

INSERT INTO marks (first_name, last_name, mark) VALUES ('Fred', 'Jones', 78);INSERT INTO marks (first_name, last_name, mark) VALUES ('Bill', 'James', 67);INSERT INTO marks (first_name, last_name, mark) VALUES ('Carol', 'Smith', 82);INSERT INTO marks (first_name, last_name, mark) VALUES ('Bob', 'Duncan', 60);INSERT INTO marks (first_name, last_name, mark) VALUES ('Joan', 'Davis', 86);

Page 37: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3737

Executing The ScriptExecuting The Script

• within MySQL use a command such aswithin MySQL use a command such as

– source c:/.........../marks.sqlsource c:/.........../marks.sql

• This adds the This adds the marksmarks table to the table to the testtest databasedatabase

Page 38: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3838

The Marks Table The Marks Table

• Selecting the complete tableSelecting the complete table

SELECT * FROM marks;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 1 | Fred | Jones | 78 || 2 | Bill | James | 67 || 3 | Carol | Smith | 82 || 4 | Bob | Duncan | 60 || 5 | Joan | Davis | 86 |+-----------+------------+-----------+------+5 rows in set (0.00 sec)

Page 39: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 3939

The WHERE Clause (1)The WHERE Clause (1)

• Select rows according to some criterionSelect rows according to some criterion

SELECT * FROM marks WHERE studentID > 1 AND studentID < 5;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 2 | Bill | James | 67 || 3 | Carol | Smith | 82 || 4 | Bob | Duncan | 60 |+-----------+------------+-----------+------+3 rows in set (0.01 sec)

Page 40: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4040

The WHERE Clause (2)The WHERE Clause (2)

• Select rows with marks >= 80Select rows with marks >= 80

SELECT * FROM marks WHERE mark >= 80;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 3 | Carol | Smith | 82 || 5 | Joan | Davis | 86 |+-----------+------------+-----------+------+2 rows in set (0.00 sec)

Page 41: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4141

The ORDER BY ClauseThe ORDER BY Clause

• Select rows according to some criterionSelect rows according to some criterionSELECT * FROM marks ORDER BY mark DESC;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 5 | Joan | Davis | 86 || 3 | Carol | Smith | 82 || 1 | Fred | Jones | 78 || 2 | Bill | James | 67 || 4 | Bob | Duncan | 60 |+-----------+------------+-----------+------+5 rows in set (0.00 sec)

Page 42: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4242

Searching Using LIKE (1)Searching Using LIKE (1)

• LIKE is used to search a table for values LIKE is used to search a table for values containing a search string:containing a search string:

• There are two wild-card characters used There are two wild-card characters used to specifiy patterns:to specifiy patterns:– _ matches a single character_ matches a single character– % matches zero or more characters% matches zero or more characters

• Can also use NOT LIKECan also use NOT LIKE

• Searching is case insensitiveSearching is case insensitive

Page 43: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4343

Searching Using LIKE (2)Searching Using LIKE (2)

• Example: last names in marks table that Example: last names in marks table that begin with Jbegin with J

• Example: first names that have 3 lettersExample: first names that have 3 letters

SELECT * FROM marks WHERE last_name LIKE 'J%';

SELECT * FROM marks WHERE first_name LIKE '_ _ _';

Page 44: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4444

Quoting stringsQuoting strings

• If a string contains a single quote it must If a string contains a single quote it must be backquoted (escaped) before it can be be backquoted (escaped) before it can be used in a queryused in a query

• Example: find records containing Example: find records containing O'ReillyO'Reilly in the in the last_namelast_name field. field.

SELECT * FROM marks WHERE last_name = 'O\'Reilly';

Page 45: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4545

Limiting number of rowsLimiting number of rows

•LIMITLIMIT can be used to specify the can be used to specify the maximum number of rows that are to be maximum number of rows that are to be returned by a select query. Examplereturned by a select query. Example– SELECTSELECT * * FROMFROM marks marks LIMITLIMIT 3; 3;

• This query will return only the first 3 rows This query will return only the first 3 rows from the from the marksmarks table table

• To return 15 rows beginning at row 5 useTo return 15 rows beginning at row 5 use– SELECTSELECT * * FROMFROM marks marks LIMITLIMIT 4, 15; 4, 15;

Page 46: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4646

MySQL Functions (1)MySQL Functions (1)

• How many rows are there ?How many rows are there ?

• Can use Can use COUNTCOUNT(marks)(marks) instead of instead of COUNTCOUNT(*)(*)

SELECT COUNT(*) FROM marks;

+----------+| COUNT(*) |+----------+| 5 |+----------+1 row in set (0.00 sec)

Page 47: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4747

MySQL Functions (2)MySQL Functions (2)

• What is the sum of all the marks?What is the sum of all the marks?

SELECT SUM(mark) FROM marks;

+-----------+| SUM(mark) |+-----------+| 373 |+-----------+1 row in set (0.00 sec)

Page 48: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4848

MySQL Functions (3)MySQL Functions (3)

• What is the average mark?What is the average mark?

SELECT AVG(mark) FROM marks;

+-----------+| AVG(mark) |+-----------+| 74.6000 |+-----------+1 row in set (0.00 sec)

Page 49: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 4949

MySQL Functions (4)MySQL Functions (4)

• What is the minimum mark?What is the minimum mark?

SELECT MIN(mark) FROM marks;

+-----------+| MIN(mark) |+-----------+| 60 |+-----------+1 row in set (0.00 sec)

Page 50: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5050

MySQL Functions (5)MySQL Functions (5)

• What is the maximum mark?What is the maximum mark?

SELECT MAX(mark) FROM marks;

+-----------+| MAX(mark) |+-----------+| 86 |+-----------+1 row in set (0.00 sec)

Page 51: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5151

books.sql (1)books.sql (1)isbn title author pub year price

USE web_db;CREATE TABLE books ( isbn CHAR(15) PRIMARY KEY NOT NULL, title VARCHAR(100) NOT NULL, author VARCHAR(100) NOT NULL, pub VARCHAR(20) NOT NULL, year YEAR NOT NULL, price DECIMAL(9,2) DEFAULT NULL);

bookstable

this is asimpledesign

Page 52: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5252

books.sql (2) books.sql (2) -- Insert some books into books table

INSERT INTO books VALUES ('0-672-31784-2', 'PHP and MySQL Web Development', 'Luke Welling, Laura Thomson', 'Sams', 2001, 74.95);

INSERT INTO books VALUES ('1-861003-02-1', 'Professional Apache', 'Peter Wainwright', 'Wrox Press Ltd', 1999, 74.95);

Page 53: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5353

Executing The ScriptExecuting The Script

• within MySQL use a command such aswithin MySQL use a command such as

– source c:/.........../books.sqlsource c:/.........../books.sql

• This adds the books table to the This adds the books table to the web_dbweb_db databasedatabase

Page 54: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5454

employee_db.sql (1)employee_db.sql (1)employeeID name position address

CREATE DATABASE IF NOT EXISTS employee_db;USE employee_db;DROP TABLE IF EXISTS employees;DROP TABLE IF EXITS jobs;

employeeID hours

employeestable

jobstable

Page 55: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5555

employee_db.sql (1)employee_db.sql (1)CREATE TABLE employees ( employeeID SMALLINT NOT NULL, name VARCHAR(20) NOT NULL, position VARCHAR(20) NOT NULL, address VARCHAR(40) NOT NULL, PRIMARY KEY (employeeID));INSERT INTO employees VALUES (1001, 'Fred', 'programmer', '13 Windle St');INSERT INTO employees VALUES (1002, 'Joan', 'programmer', '23 Rock St');INSERT INTO employees VALUES (1003, 'Bill', 'manager', '37 Front St');

Page 56: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5656

employee_db.sql (2)employee_db.sql (2)CREATE TABLE jobs ( employeeID SMALLINT NOT NULL, hours DECIMAL(5,2) NOT NULL,);INSERT INTO jobs VALUES (1001, 13.5);INSERT INTO jobs VALUES (1002, 2);INSERT INTO jobs VALUES (1002, 6.25);INSERT INTO jobs VALUES (1003, 4);INSERT INTO jobs VALUES (1001, 1);INSERT INTO jobs VALUES (1003, 7);INSERT INTO jobs VALUES (1003, 9.5);

Page 57: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5757

Executing The ScriptExecuting The Script

• within MySQL use a command such aswithin MySQL use a command such as

– source c:/......./employee_db.sqlsource c:/......./employee_db.sql

• This creates the This creates the employee_dbemployee_db database database and adds the employees and jobs tables and adds the employees and jobs tables to itto it

Page 58: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5858

Select Queries With Joins (1)Select Queries With Joins (1)

• Cartesian product queryCartesian product query

SELECT * FROM employees, jobs;

+------------+------+------------+--------------+------------+-------+| employeeID | name | position | address | employeeID | hours |+------------+------+------------+--------------+------------+-------+| 1001 | Fred | programmer | 13 Windle St | 1001 | 13.50 || 1002 | Joan | programmer | 23 Rock St | 1001 | 13.50 || 1003 | Bill | manager | 37 Front St | 1001 | 13.50 || 1001 | Fred | programmer | 13 Windle St | 1002 | 2.00 || 1002 | Joan | programmer | 23 Rock St | 1002 | 2.00 || 1003 | Bill | manager | 37 Front St | 1002 | 2.00 || 1001 | Fred | programmer | 13 Windle St | 1002 | 6.25 || 1002 | Joan | programmer | 23 Rock St | 1002 | 6.25 || 1003 | Bill | manager | 37 Front St | 1002 | 6.25 |

Page 59: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 5959

Select Queries With Joins (2)Select Queries With Joins (2)

• Cartesian product query (continued)Cartesian product query (continued)| 1001 | Fred | programmer | 13 Windle St | 1003 | 4.00 || 1002 | Joan | programmer | 23 Rock St | 1003 | 4.00 || 1003 | Bill | manager | 37 Front St | 1003 | 4.00 || 1001 | Fred | programmer | 13 Windle St | 1001 | 1.00 || 1002 | Joan | programmer | 23 Rock St | 1001 | 1.00 || 1003 | Bill | manager | 37 Front St | 1001 | 1.00 || 1001 | Fred | programmer | 13 Windle St | 1003 | 7.00 || 1002 | Joan | programmer | 23 Rock St | 1003 | 7.00 || 1003 | Bill | manager | 37 Front St | 1003 | 7.00 || 1001 | Fred | programmer | 13 Windle St | 1003 | 9.50 || 1002 | Joan | programmer | 23 Rock St | 1003 | 9.50 || 1003 | Bill | manager | 37 Front St | 1003 | 9.50 |+------------+------+------------+--------------+------------+-------+21 rows in set (0.01 sec)

The cartesian product query is rarely what we want.

Page 60: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 6060

Select Queries With Joins (3)Select Queries With Joins (3)

• SubstitutionSubstitution

+------+-------+| name | hours |+------+-------+| Fred | 13.50 || Joan | 2.00 || Joan | 6.25 || Bill | 4.00 || Fred | 1.00 || Bill | 7.00 || Bill | 9.50 |+------+-------+

7 rows in set (0.00 sec)

Here we are replacing the employeeID

numbers in the jobs table by the employee's

name

SELECT name, hours FROM employees, jobs WHEREemployees.employeeID = jobs.employeeID;

Page 61: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 6161

Select Queries With Joins (4)Select Queries With Joins (4)

• Entries only for FredEntries only for Fred

+------+-------+| name | hours |+------+-------+| Fred | 13.50 || Fred | 1.00 |+------+-------+

2 rows in set (0.00 sec)

SELECT name, hours FROM employees, jobs WHEREemployees.employeeID = jobs.employeeID ANDname = 'Fred';

Page 62: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 6262

Select Queries With Joins (5)Select Queries With Joins (5)

• Total hours worked for each personTotal hours worked for each person

+------+------------+| name | SUM(hours) |+------+------------+| Bill | 20.50 || Fred | 14.50 || Joan | 8.25 |+------+------------+3 rows in set (0.00 sec)

SELECT name, SUM(hours) FROM employees, jobsWHERE employees.employeeID = jobs.employeeIDGROUP BY name;

Page 63: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 6363

Select Queries With Joins (6)Select Queries With Joins (6)

• Total hours worked, for FredTotal hours worked, for Fred

+------+------------+| name | SUM(hours) |+------+------------+| Fred | 14.50 |+------+------------+1 row in set (0.00 sec)

SELECT name, SUM(hours) FROM employees, jobsWHERE employees.employeeID = jobs.employeeIDAND name = 'Fred' GROUP BY name;

Page 64: MySQL Database System Hiep Dinh

04/09/1004/09/10 BGABGA 6464

SQL linksSQL links

• TutorialsTutorials– http://www.w3schools.com/sql/http://www.w3schools.com/sql/– http://www.sqlzoo.nethttp://www.sqlzoo.net – http://sqlcourse.comhttp://sqlcourse.com (part 2) (part 2)– http://sqlcourse2/comhttp://sqlcourse2/com (part 1) (part 1)

• MySQL online reference manualMySQL online reference manual– http://dev.mysql.com/doc/mysql/en/Reference.htmlhttp://dev.mysql.com/doc/mysql/en/Reference.html