Você está na página 1de 8

Library tutorials & articles

MySQL Tutorial
By Gez Lemon, published on 03 Sep 2003 Comments (5) PDF

Introduction
Released in January 1998, MySQL is an open source relational database management system (RDBMS). It's based around the Structured Query Language (SQL), and is
best for managing the content of the database as opposed to transactions, as MySQL does not support COMMIT or ROLLBACK. One of the biggest drawbacks of MySQL
is it's lack of support for referential integrity, no stored procedures, no triggers, and no sub-queries. MySQL is free, and may be downloaded from download section at
MySQL.

Getting Started
When you start using MySQL, you use a command prompt to enter the SQL statement. The statements can be quite lengthy, and a pain to modify. The simplest way of
using MySQL is to use files containing the SQL statements to perform. For example, if you want to create a table called, search, you could create a file called called,
createSearchTable.sql and load this file from the command prompt rather than type in a lengthy SQL statement to create the table.

Loading SQL Statements from a File

The SOURCE command is used to load the file from the command prompt.

mysql> SOURCE createSearchTable.sql

The sequence \. is a shorcut name for the SOURCE statement. The following does exactly the same thing as the above SOURCE statement.

mysql> \. createSearchTable.sql

Logging Output

The TEE statement may be used to log output from your SQL statements to a text file. The following command copies all output to the file log.txt so you can examine the
results of running your queries.

mysql> TEE log.txt

You can turn off loging using the NOTEE statement.

mysql> NOTEE

Creating and Deleting Databases


Creating a Database

The CREATE statement is used to create a database in MySQL. The following statement creates a database called search.

mysql> CREATE DATABASE search;

To let MySQL know that you want to use that database, you use the USE statement. The following example uses the database, search.

mysql> USE search;

Deleting a Database

Databases can be deleted using the DROP statement. The following example deletes the database, search.

mysql> DROP DATABASE search;

Creating Tables
The CREATE statement is used to create a table in MySQL. The general syntax to create a table in MySQL is:

CREATE TABLE tableName


(
fieldName1 dataType(size) [NULL | NOT NULL]
fieldName2 dataType(size) [NULL | NOT NULL]
);

If NULL is specified, the field is allowed to be left empty. If NOT NULL is specified, the field must be given a value. In the absence of either a NULL or NOT NULL, NULL is
assumed.

Data Types of Fields

The following lists the data types avaiable in MySQL.

Data Type Example Description

CHAR(size fieldName CHAR(10) Stores up to 255 characters. If the content is smaller than the field size, the content will have trailing spaces appended.
VARCHAR fieldName VARCHAR Stores up to 255 characters, and a minimum of 4 characters. No trailing spaces are appended to the end of this datatype. MySQL keeps track
(size (100) of a delimiter to keep track of the end of the field.

TINYTEXT fieldName TINYTEXT Stores up to 255 characters. Equivalent to VARCHAR(255).

TEXT fieldName TEXT Stores up to 65,535 characters. An Index can be created on the first 255 characters of a field with this data type.

fieldName Stores up to 16,777,215 characters. An Index can be created on the first 255 characters of a field with this data type.
MEDIUMTEXT
MEDIUMTEXT

Stores up to 4,294,967,295 characters. An Index can be created on the first 255 characters of a field with this data type.
LONGTEXT fieldName LONGTEXT
Note: The maximum size of a string in MySQL is currently 16 million bytes, so this data types is not useful at the moment.

fieldName ENUM Stores up to 65,535 enumerated types. The DEFAULT modifier may be used to specify the default value for this field.
ENUM
('Yes', 'No')

Stores a signed or unsigned integer number. Unsigned integers have a range of 0 to 4,294,967,295, and signed integers have a range of -
2,147,438,648 to 2,147,438,647. By default, the INT data type is signed. To create an unsigned integer, use the UNSIGNED attribute.

fieldName INT UNSIGNED


The ZEROFILL attribute may be used to left-pad any of the integer with zero's.
INT fieldName INT
fieldName INT ZEROFILL
The AUTO_INCREMENT attribute may be used with any of the Integer data types. The following example could be used to create a primary key
using the AUTO_INCREMEMNT attribute.

fieldName INT UNSIGNED AUTO_INCREMENT PRIMARY KEY

Stores a signed or unsigned byte. Unsigned bytes have a range of 0 to 255, and signed bytes have a range of -128 to 127. By default, the
TINYINT fieldName TINYINT TINYINT data type is signed.

fieldName Stores a signed or unsigned medium sized integer. Unsigned fields of this type have a range of 0 to 1,677,215, and signed fields of this type
MEDIUMINT have a range of -8,388,608 to 8,388,607. By default, the MEDIUMINT data type is signed.
MEDIUMINT

Stores a signed or unsigned big integer. Unsigned fields of this type have a range of 0 to 18,446,744,073,709,551,615, and signed fields of this
BIGINT fieldName BIGINT type have a range of -9,223,372,036,854,775,808 to 9,223,327,036,854,775,807. By default, the BIGINT data type is signed.

FLOAT fieldName FLOAT Used for single precision floating point numbers.

DOUBLE fieldName DOUBLE Used for double precision floating point numbers.

DATE fieldName DATE Stores dates in the format YYYY-MM-DD.

TIMESTAMP
fieldName DATETIME Stores dates and times in the format YYYY-MM-DD HH:MM:SS.
(size)

Automatically keeps track of the time the record was last ammended. The following table shows the formats depending on the size of
TIMESTAMP

Size Format

2 YY

4 YYMM
fieldName
DATETIME 6 YYMMDD
TIMESTAMP(14)
8 YYYYMMDD

10 YYYYMMDDHH

12 YYYYMMDDHHMM

14 YYYYMMDDHHMMSS

TIME fieldName TIME Stores times in the format HH:MM:SS.

YEAR(size) fieldName YEAR(4) Stores the year as either a 2 digit number, or a 4 digit number, depending on the size provided.

Primary Keys

A primary key is a field in a table that uniquely identifies a record. The PRIMARY KEY attribute may be used when defining the field name to create a primary key, as in the
following example.

fieldName INT UNSIGNED AUTO_INCREMENT PRIMARY KEY

Alternatively, the PRIMARY KEY attribute may be used to specify the primary key after the defining the fields, as in the following example:

CREATE TABLE product


(
prodID INT UNSIGNED AUTO_INCREMENT,
description VARCHAR(100),
PRIMARY KEY(prodID)
);

The second method is ideal should you want to create a compound primary key. A compound primary key is where more than one field is used to uniquely identify a
unique record. The field names are separated with commas. Consider a table used with a search engine for a site. The primary key could comprise the Directory name,
and the page name. The following example illustrates creating a table with a compound primary key.

createSearch.sql
CREATE TABLE search
(
Category VARCHAR(100) NOT NULL,
Page VARCHAR(20) NOT NULL,
Directory VARCHAR(255) NOT NULL,
LinkName VARCHAR(255) NOT NULL,
Keywords MEDIUMTEXT NOT NULL,
Desription VARCHAR(255) NOT NULL,
PRIMARY KEY(Page, Directory)
);

The file may then be used with MySQL as follows:

mysql> \. createSearch.sql

Providing Default Values

Default values may be provided for fields using the DEFAULT attribute. The following example uses a default value of index.html, should a Page name not be provided for
the search table.

createSearch.sql

CREATE TABLE search


(
Category VARCHAR(100) NOT NULL,
Page VARCHAR(20) DEFAULT 'index.html',
Directory VARCHAR(255) NOT NULL,
LinkName VARCHAR(255) NOT NULL,
Keywords MEDIUMTEXT NOT NULL,
Desription VARCHAR(255) NOT NULL,
PRIMARY KEY(Page, Directory)
);

Examining Tables

You can examine the structure of a table using the DESCRIBE statement. The following displays the structure of the search table.

mysql> DESCRIBE search;

The DESCRIBE statement may be shorted to DESC. The following achieves the same thing.

mysql> DESC search;

You may also use the SHOW FIELDS FROM statement to achieve the same thing.

mysql> SHOW FIELDS FROM search;

Listing All Tables

You can list all tables in the database using the SHOW TABLES statement. The following example lists all tables in the current database.

mysql> SHOW TABLES;

Using Indexes
Creating an Index

Indexes allow you to specify an index for a table to speed up searching. Primary keys are automatically indexed, but you can add indexes to other fields to allow them to be
easily searchable. The database has to maintain the indexes, so it's not a good idea to make every field an index. The following example provides an index called
keyIndex for a field called keywords.

INDEX keyIndex(Kewords)

You can specify how many characters you wish to index in a field. The following example creates an index on the first 100 characters of the field, Keywords.

INDEX keyIndex(Keywords(100))

Creating a Compound Index

You can create an index on more than one table by specifying a comma separated list. The following example creates a compound index on the first 100 characters of the
Keywords field, and the Description field.

INDEX compoundIndex(Keywords(100), Description)

The indexes are from left to right. Therefore, in the example, indexes are only created for Descriptions where Keywords exist.

Creating Unique Indexes

The UNIQUE specifier may be used to ensure that indexes are unique. The following example requires that the values assigned to the first 100 characters of the
Keywords field are unique.

UNIQUE INDEX keyIndex(Keywords(100))

The following example creates a table called search, with an Index on the first 100 characters of the Keywords field.

createSearch.sql

CREATE TABLE search


(
Category VARCHAR(100) NOT NULL,
Page VARCHAR(20) NOT NULL,
Directory VARCHAR(255) NOT NULL,
LinkName VARCHAR(255) NOT NULL,
Kewords MEDIUMTEXT NOT NULL,
Desription VARCHAR(255) NOT NULL,
PRIMARY KEY(Page, Directory),
INDEX keyIndex(Keywords(100))
);

The file may then be used with MySQL as follows:

mysql> \. createSearch.sql

Altering Tables
The ALTER TABLE command allows you to alter tables, fields and indexes of a table.

Renaming a Table

The RENAME modifier allows you to rename a table. The following example renames the table search to site.

mysql> ALTER TABLE search RENAME site;

Adding Columns to a Table

The ADD COLUMN modifier allows you to add a column to a table. The following example adds a field called modified to the search table.

mysql> ALTER TABLE search ADD COLUMN modified TIMESTAMP;

The FIRST and AFTER modifiers may be used to position the field within the table. The following places the new field as the first field in the table.

mysql> ALTER TABLE search ADD COLUMN modified TIMESTAMP FIRST;

The next example could be used to add the new field immediately after the field Keywords.

mysql> ALTER TABLE search ADD COLUMN modified TIMESTAMP AFTER Keywords;

Dropping a Column from a Table

The DROP COLUMN modifier may be used to drop a column from the table. The following example drops the field modified.

mysql> ALTER TABLE search DROP COLUMN modified;

Dropping a Indexes from a Table

The DROP INDEX modifier may be used to drop an index from a table. The following example drops the index keyIndex from the search table.

mysql> ALTER TABLE search DROP INDEX keyIndex;

Modifying columns

When you modify a column, you must specify the attributes for the column again. The following example renames the Description field to PageDescription in the search
table.

mysql> ALTER TABLE search CHANGE Description PageDescription VARCHAR(255) NOT NULL;

If you only want to change the attributes, use the same column name as in the following example:

mysql> ALTER TABLE search CHANGE Description Description VARCHAR(200) NOT NULL;

Deleting a Table

Tables are deleted from the database using the DROP statement. The following example drops the table search from the database.

mysql> DROP TABLE search;

The SELECT statement


The select query is used to retrieve records from a database. The keywords used in a select query are summarised in the following table.

Keyword Description

SELECT Retrieves fields from one or more tables.

FROM Tables containing the fields.

WHERE Criteria to restrict the records returned.

GROUP BY Determines how the records should be grouped.

HAVING Used with GROUP BY to specify the criteria for the grouped records.

ORDER BY Criteria for ordering the records.

LIMIT Limit the number of records returned.

The simplest SELECT query is to retrieve all records from a single table. The following example lists all fields from the search table.

mysql> SELECT * FROM search;

To select specific fields from a table, you provide a comma-separated list of field names. The following example selects the Page and Directory from the search table:
mysql> SELECT Page, Directory FROM search;

Limiting Records
The WHERE clause may be used to limit records. The following lists the comparison operators available with MySQL to limit the records returned with the WHERE clause.

Operator Description

= Equal to

<> or != Not equal to

< Less than

<= Less than or equal to

> greater than

>= greater than or equal to

LIKE Used to compare strings

BETWEEN Checks for values between a range

IN Checks for values in a list

NOT IN Ensures the value is not in the list

When working with strings, the % character may be used as a wildcard. The following example retrieves all fields from the search table where the Keyword field contains
the text, "cookies".

mysql> SELECT * FROM search WHERE Keywords LIKE '%cookies%';

The underscore character may be used as a placeholder. The following example selects all records from the search table, where the Page name beings with 'P', followed
by four characters (four underscores are used).

mysql> SELECT * FROM search WHERE Page LIKE 'P____';

The BETWEEN clause may be used with numbers, dates and text. The following example retrieves all fields from Products, where the cost is between 1000 and 4000.

mysql> SELECT * FROM Products WHERE cost BETWEEN 1000 AND 4000;

The OR clause may be used to specify a range of values to check against. The following example lists all records where the Category is either ASP or PHP in the search
table.

mysql> SELECT * FROM search WHERE Category = 'ASP' OR Category = 'PHP';

If you have many values that you want to check against, you can use the IN clause as it makes the code a lot more readable. The following is the above statement using
the IN clause.

mysql> SELECT * FROM search WHERE Category IN ('ASP', 'PHP');

Similarly, you can use the NOT modifier with the IN clause to check for values that are not within the list. The following example returns all records where the Category is
not equal to ASP or PHP

mysql> SELECT * FROM search WHERE Category NOT IN ('ASP', 'PHP');

Joining Tables
Sometimes the data you require may come from two or more tables. Supposing our search table contained a foreign key called AuthorID that related to a primary key of
the same name in an author table, we could retrieve records by linking the two fields. The following example lists the Surname and Forename from an author table, and
the Directory and Page from the search table written by that author.

SELECT author.Surname, author.Forename, search.Directory, search.Page FROM search,


author WHERE author.AuthorID = search.AuthorID;

You can add further clauses to the WHERE clause, using the AND operator. The following example extends the previous example to return only records where the Author
has the Surname, Lemon.

listLemons.sql
SELECT author.Surname, author.Forename, search.Directory, search.Page FROM search, author WHERE author.AuthorID = search.AuthorID
AND author.Surname = 'Lemon';
The file may then be used with MySQL as follows:

mysql> \. listLemons.sql

Selecting Distinct Records


Our "search" table contains a list of pages in directories. If we were to list all directories from the table, we would end up with duplicate records, as there may be more
than one page in a directory. The DISTINCT modifier may be used to ensure that one one record is returned for each Directory name.

mysql> SELECT DISTINCT Directory FROM search;

Aggregate Functions
The GROUP BY modifier may be used to perform aggregate functions, such as COUNT records. The following example lists the distinct Directories, along with a count of
how many records there are for that Directory in the search table.
mysql> SELECT Directory, COUNT(*) FROM search GROUP BY Directory;

The AS modifier may be used to provide meaningful column names for the result. In the above example, the column headings from running the query are, Directoy and
COUNT(*). The following example uses the column name Entries instead of COUNT(*).

mysql> SELECT Directory, COUNT(*) AS Entries FROM search GROUP BY Directory;

If you want the column name to contain spaces, you must put the name in single quotes. The next example uses a column name of Number of Entries.

mysql> SELECT Directory, COUNT(*) AS 'Number of Entries' FROM search GROUP BY Directory;

List of Aggregate Functions Available in MySQL


The following table contains a list of the aggregate function available in MySQL.

Function Example Description

SELECT AVG(cost) FROM Invoice GROUP BY Returns the average value in a group of records. The example returns the average order for each
AVG() customer.
ClientID;

SELECT COUNT(cost) FROM Invoice GROUP BY Returns the number of records in a group of records. The example returns the number of orders for each
COUNT() customer.
ClientID;

SELECT MAX(cost) FROM Invoice GROUP BY Returns the largest value in a group of records. The example returns the largest order by each customer.
MAX()
ClientID;

SELECT MIN(cost) FROM Invoice GROUP BY Returns the lowest value in a group of records. The example returns the smallest order by each customer.
MIN()
ClientID;

SELECT SUM(cost) FROM Invoice GROUP BY Returns the sum of a field. The example returns the total amount spent by each customer.
SUM()
ClientID;

The Having Clause


The WHERE clause is used to restrict records in a query. If you wish to restrict records from an aggregate function, you use the HAVING clause. The difference is that the
HAVING clause restricts the records after they have been grouped. The following lists all customers who have spent over 20,000 on average.

mysql> SELECT AVG(cost) FROM Invoice GROUP BY ClientID HAVING AVG(cost) > 20000;

The Order By Clause


The ORDER BY clause may be used to order the records returned. The following example lists all Pages in the search table in alphabetical order.

mysql> SELECT Page FROM search ORDER BY Page;

The ORDER BY clause may use the ASC or DESC modifiers to determine if the records should be in ascending or descending order. If neither are provided, the records are
shown in ascending order. The following example lists all Pages in the search table in descending order.

mysql> SELECT Page FROM search ORDER BY Page DESC;

Limiting the Records Returned


The LIMIT clause may be used to limit the records returned by the SELECT statement. You specify the start row (start from zero), and the number of records returned. The
following example lists the first 10 records from the search table.

mysql> SELECT * FROM search LIMIT 0, 10;

The following example would retrieve the next ten records from the search table.

mysql> SELECT * FROM search LIMIT 10, 10;

The INSERT statement


The insert statement is used to insert records into a table. The keywords used in an insert statement are summarised in the following table.

Keyword Description

INSERT Inserts data into a table

INTO Specifies the name of the table to insert the data

VALUES The data for the fields in the table

The following example inserts two records into the search table.

insert.sql

INSERT INTO search (Category,


Page,
Directory,
LinkName,
Keywords,
Description)
VALUES ('ASP',
'cookies.html',
'http://www.juicystudio.com/tutorial/asp/',
'Reading Cookies',
'request,cookies,key,subkey,domain',
'Using the Request object to read cookies in ASP');
INSERT INTO search (Category,
Page,
Directory,
LinkName,
Keywords,
Description)
VALUES ('PHP',
'cookies.html',
'http://www.juicystudio.com/tutorial/php/',
'Using Cookies',
'cookies,setting,retrieving,reading,setcookie,isset',
'Using cookies in PHP');

The file may then be used with MySQL as follows:

mysql> \. insert.sql

If a field in your table allows NULL values, you may omit the field from the INSERT statement.

Characters that require Escaping

The following characters have a special meaning to MySQL, and will need to be escaped by putting a backslash before them in order that they are interpreted correctly.

Characters Name

' Single quote

" Double quote

\ Blackslash

% Percent

_ Underscore

The following example shows how you would escape an underscore in the string, "last_modified".

'last\_modified'

You can escape single quotes by placing two single quotes together, as in the following example.

'Don''t care!'

The UPDATE statement


The update statement is used to update records in a database. The keywords used in an update statement are summarised in the following table.

Keyword Description

UPDATE Updates data in one or more tables.

SET Specifies the field names to be updates. If the fields belong to more that one table, the table name should be specified before the field name. (eg. search.Page).

WHERE Criteria to restrict the records updated.

The following example updates all records in the search table to change the category from Jive, to Java.

update.sql

UPDATE search
SET Category = 'Java'
WHERE Category = 'Jive';

The file may then be used with MySQL as follows:

mysql> \. update.sql

The same characters need escaping as mentioned on the previous page.

The DELETE statement


The delete statement is used to delete records in a database. The keywords used in a delete statement are summarised in the following table.

Keyword Description

DELETE Deletes the records in one or more tables.

FROM Tables containing the records.

WHERE Criteria to restrict the records deleted.

The following example deletes all records in the search table where the category is Junk.

delete.sql

DELETE FROM search


WHERE Category = 'Junk';

The file may then be used with MySQL as follows:

mysql> \. delete.sql

Related tags
php, mysql, sql

© 1999-2010 Developer Fusion Ltd Web hosting by UKFast

Você também pode gostar