Documente Academic
Documente Profesional
Documente Cultură
1. OBJECTIVE
The objective of the mysql training book is to learn the database programming of mysql in a
detailed formats clearly and efficiently.
2. INTRODUCTION
MySQL is the most popular Open Source Relational SQL database management system. MySQL
is one of the best RDBMS being used for developing web-based software applications.
A database is a structured collection of data. It may be anything from a simple shopping list to a
picture gallery or the vast amounts of information in a corporate network. To add, access, and
process data stored in a computer database, you need a database management system such as
MySQL Server.
The MySQL Database Server is very fast, reliable, scalable, and easy to use:
If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a
desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no
attention.
For portability, uses CMake in MySQL 5.5 and up. Previous series use GNU Automake,
Autoconf, and Libtool.
Security
A privilege and password system that is very flexible and secure, and that enables host-
based verification.
Password security by encryption of all password traffic when you connect to a server.
Connectivity:
Localization:
Full support for several different character sets, including latin1 (cp1252), german, big5, ujis,
several Unicode character sets, and more. For example, the Scandinavian characters “å”, “ä” and
“ö” are permitted in table and column names.
If the administrator creates your database for you when setting up your permissions, you can begin
using it. Otherwise, you need to create it yourself:
mysql> CREATE DATABASE poll;
CREATING A TABLECreating a database does not select it for use; you must do that explicitly. To
make menagerie the current database, use this statement:
what_to_select indicates what you want to see. This can be a list of columns, or * to indicate “all
columns.” which_table indicates the table from which you want to retrieve data. The WHERE
clause is optional. If it is present, conditions_to_satisfy specifies one or more conditions that rows
must satisfy to qualify for retrieval.
4. COMMON QUERIES
Mysql queries are usually written once and then wrapped in class functions to minimize code
repetition. Mysql queries are usually written once and then wrapped in class functions to minimize
code repetition.
Other solutions are to use a LEFT JOIN or to sort all rows descending by price and get only the first
row using the MySQL-specific LIMIT clause:
FROM shop s1
FROM shop s2
+---------+--------+-------+
+---------+--------+-------+
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | C | 1.69 |
| 0004 | D | 19.95 |
+---------+--------+-------+
The preceding example uses a correlated subquery, which can be inefficient. Other possibilities for
solving the problem are to use an uncorrelated subquery in the FROM clause or a LEFT JOIN.
Uncorrelated subquery:
FROM shop s1
JOIN (
FROM shop
GROUP BY article) AS s2
LEFT JOIN:
FROM shop s1
You can employ MySQL user variables to remember results without having to store them in tem
porary variables in the client.
For example, to find the articles with the highest and lowest price you can do this:
+---------+--------+-------+
+---------+--------+-------+
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:
);
('dog'),('cat'),('penguin'),
('lax'),('whale'),('ostrich');
Which returns:
+----+---------+
| id | name |
+----+---------+
| 1 | dog |
| 2 | cat |
| 3 | penguin |
| 4 | lax |
| 5 | whale |
| 6 | ostrich |
+----+---------+
Range Optimization
IS NULL Optimization
ORDER BY Optimization
GROUP BY Optimization
DISTINCT Optimization
Subquery Optimization
Queries, in the form of SELECT statements, perform all the lookup operations in the database.
Tuning these statements is a top priority, whether to achieve sub-second response times for
dynamic web pages, or to chop hours off the time to generate huge overnight reports.
Besides SELECT statements, the tuning techniques for queries also apply to constructs such as
CREATE TABLE...AS SELECT, INSERT INTO...SELECT, and WHERE clauses in DELETE
statements. Those statements have additional performance considerations because they combine
write operations with the read-oriented query operations.
To optimize insert speed, combine many small operations into a single large operation. Ideally, you
make a single connection, send the data for many new rows at once, and delay all index updates
and consistency checking until the very end. The time required for inserting a row is determined by
the following factors, where the numbers indicate approximate proportions:
1) Connecting: (3)
6) Closing: (1)
The time required to delete individual rows in a MyISAM table is exactly proportional to the number
of indexes. To delete rows more quickly, you can increase the size of the key cache by increasing
the key_buffer_size system variable. See Section 6.1.1, “Configuring the Server”. To delete all
rows from a MyISAM table, TRUNCATE TABLE tbl_name is faster than DELETE FROM tbl_name.
Truncate operations are not transaction-safe; an error occurs when attempting one in the course of
an active transaction or active table lock.
The best way to improve the performance of select operations is to create indexes on one or more
of the columns that are tested in the query. The index entries act like pointers to the table rows,
allowing the query to quickly determine which rows match a condition in the where clause, and
retrieve the other column values for those rows. All mysql data types can be indexed
If your table is big and important, but does not have an obvious column or set of columns to use as
a primary key, you might create a separate column with auto-increment values to use as the
primary key. These unique IDs can serve as pointers to corresponding rows in other tables when
you join tables using foreign keys.
Since the performance requirements to retrieve and display a BLOB value might be very different
from other data types, you could put the BLOB-specific table on a different storage device or even
a separate database instance. For example, to retrieve a BLOB might require a large sequential
disk read that is better suited to a traditional hard drive than to an SSD device.
8. DATA TYPES
Mysql supports a number of sql data types in several categories: numeric types, date and time
types, string (character and byte) types, and spatial types. This chapter provides an overview of
these data types, a more detailed description of the properties of the types in each category, and a
summary of the data type storage requirements
1. BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.
2. BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
4. BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero
values are considered true:
MEDIUMINT 3 -8388608 0
8388607 16777215
INT 4 2147483648 0
2147483647 4294967295
Example:
the syntax type_name(fsp), where type_name is TIME, DATETIME, or TIMESTAMP, and fsp is the
fractional seconds precision. For example:
CREATE TABLE t1 (t TIME(3), dt DATETIME(6));
The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional
part. If omitted, the default precision is 0. (This differs from the standard SQL default of 6, for
compatibility with previous MySQL versions.)
DATE
A date. The supported range is '1000-01-01' to '9999-12-31'. MySQL displays DATE values in
'YYYY-MM-DD' format, but permits assignment of values to DATE columns using either strings or
numbers.
DATETIME[(fsp)]
A date and time combination. The supported range is '1000-01-01 00:00:00.000000' to '9999-12-31
23:59:59.999999'. MySQL displays DATETIME values in 'YYYY-MM-DD HH:MM:SS[.fraction]'
format, but permits assignment of values to DATETIME
Example:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
dt DATETIME DEFAULT CURRENT_TIMESTAMP
);
time by a decimal point; no other fractional seconds delimiter is recognized. For information about
fractional seconds support in MySQL
Example:
The CHARACTER SET attribute specifies the character set, and the COLLATE attribute specifies a
collation for the character set. For example:
CREATE TABLE t
(
c1 VARCHAR(20) CHARACTER SET utf8,
);
Readable queries and output. The numbers are translated back to the corresponding strings in
query results. If you make enumeration values that look like numbers, it is easy to mix up the literal
values with their internal index numbers, as explained in Enumeration Limitations.
Using ENUM columns in ORDER BY clauses requires extra care, as explained in Enumeration
Sorting.
Creating and Using ENUM Columns
An enumeration value must be a quoted string literal. For example, you can create a table with an
ENUM column like this:
CREATE TABLE shirts (
name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
('polo shirt','small');
SELECT name, size FROM shirts WHERE size = 'medium';
+---------+--------+
| name | size |
+---------+--------+
| t-shirt | medium |
+---------+--------+
UPDATE shirts SET size = 'small' WHERE size = 'large';
COMMIT;
''
'one'
'two'
'one,two'
A SET column can have a maximum of 64 distinct members.
TINYINT 1 byte
SMALLINT 2 bytes
MEDIUMINT 3 bytes
BIGINT 8 bytes
FLOAT 4 bytes
DOUBLE 8 bytes
[PRECISION], REAL
TIME 3 bytes
3 bytes + fractional seconds
storage
TIMESTAMP 4 bytes
4 bytes + fractional seconds
storage
In the following table, M represents the declared column length in characters for nonbinary string
types and bytes for binary string types. L represents the actual length in bytes of a given string value.
CHAR data character in the character set. “Physical Row Structure of InnoDB
Tables” for information about type storage requirements for InnoDB
tables.
Variable-length string types are stored using a length prefix plus data. The length prefix requires
from one to four bytes depending on the data type, and the value of the prefix is L (the byte length of
the string). For example, storage for a MEDIUMTEXT value requires L bytes to store the value plus
three bytes to store the length of the value.
Name Description
:= Assign a value
BETWEEN ... AND ... Check whether a value is within a range of values
-> 2
It is also possible to convert a number to a string explicitly using the CAST() function. Conversion
occurs implicitly with the CONCAT() function because it expects string arguments.
mysql> SELECT 38.8, CAST(38.8 AS CHAR);
-> 38.8, '38.8'
mysql> SELECT 38.8, CONCAT(38.8);
-> 38.8, '38.8'
See later in this section for information about the character set of implicit number-to-string
conversions, and for modified rules that apply to CREATE TABLE ... SELECT statements.
10.3 OPERATORS
Operator Precedence
Operator precedences are shown in the following list, from highest precedence to the lowest.
Operators that are shown together on a line have the same precedence.
INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|
= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
NOT
AND, &&
XOR
OR, ||
= (assignment),:=
Example:
-> 7
-> 9
Name Description
BETWEEN ... AND ... Check whether a value is within a range of values
= Equal operator
Logical Operators
Name Description
||, OR Logical OR
1. AND, &&
2. NOT,!
SELECT title_id, type, price
FROM titles
WHERE NOT type = 'biography'
AND NOT price < 20;
3. ||, OR
4. XOR
SELECT EmployeeID, FirstName, LastName, ReportsTo
FROM employees
WHERE ReportsTo=2 XOR FirstName='Nancy';
In SQL, all logical operators evaluate to TRUE, FALSE, or NULL (UNKNOWN). In MySQL,
these are implemented as 1 (TRUE), 0 (FALSE), and NULL. Most of this is common to
different SQL database servers, although some servers may return any nonzero value for
TRUE.
Name Description
CEIL() Return the smallest integer value not less than the
argument
CEILING() Return the smallest integer value not less than the
argument
/ Division operator
Arithmetic Operators
Name Description
/ Division operator
- Minus operator
+ Addition operator
* Multiplication operator
Example:
Mathematical Functions
Name Description
Name Description
Add time
Examples:
1. Now():
2. Curdate():
3. Curtime():
4. Date_add():
5. Curtime():
6. Convert_TZ():
Name Description
Many encryption and compression functions return strings for which the result might contain
arbitrary byte values. If you want to store these results, use a column with a VARBINARY or BLOB
binary string data type. This will avoid potential problems with trailing space removal or character
set conversion that would change data values, such as may occur if you use a nonbinary string
data type (CHAR, VARCHAR, TEXT).
The group by clause is normally used along with five built-in, or "aggregate" functions. These
functions perform special operations on an entire table or on a set, or group, of rows rather than on
each row and then return one row of values for each group.the group by clause is normally used
along with five built-in, or "aggregate" functions. These functions perform special operations on an
entire table or on a set, or group, of rows rather than on each row and then return one row of
values for each group.
Name Description
Example 1:
Example 2:
Example 3:
Testing Table:
Test2 Table
Result:
This section describes group (aggregate) functions that operate on sets of values. Unless
otherwise stated, group functions ignore NULL values.
If you use a group function in a statement containing no GROUP BY clause, it is equivalent to
grouping on all rows. For more information, “MySQL Handling of GROUP BY”.
For numeric arguments, the variance and standard deviation functions return a DOUBLE value.
The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or
DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).
The select statement is used to select data from a database.the select statement is used to select
data from a database.
EVENT event_name
[RENAME TO new_event_name]
[COMMENT 'comment']
[DO event_body]
characteristic:
COMMENT 'string'
| LANGUAGE SQL
[WAIT]
CALL sp_name([parameter[,...]])
CALL sp_name[()]
The CALL statement invokes a stored procedure that was defined previously with CREATE
PROCEDURE.
DELETE Syntax
Single-table syntax:
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
Multiple-table syntax:
FROM table_references
[WHERE where_condition]
DESCRIBE Syntax
The DESCRIBE and EXPLAIN statements are synonyms, used either to obtain information about
table structure or query execution plans. For more information
EXPLAIN Syntax
{EXPLAIN | DESCRIBE | DESC}
tbl_name [col_name | wild]
{EXPLAIN | DESCRIBE | DESC}
[explain_type] SELECT select_options
discussion uses the DESCRIBE and EXPLAIN keywords in accordance with those uses, but the
MySQL parser treats them as completely synonymous.
HELP Syntax
HELP 'search_string'
The HELP statement returns online information from the MySQL Reference manual. Its proper
operation requires that the help tables in the mysql database be initialized with help topic
information
USE Syntax
USE db_name
The USE db_name statement tells MySQL to use the db_name database as the default (current)
database for subsequent statements. The database remains the default until the end of the session
or another USE statement is issued:
USE db1;
SELECT COUNT(*) FROM mytable; # selects from db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable; # selects from db2.mytable
This chapter discusses stored programs and views, which are database objects defined in terms of
sql code that is stored on the server for later execution.
Views are stored queries that when referenced produce a result set. A view acts as a virtual table.
Each stored program contains a body that consists of an SQL statement. This statement may be a
compound statement made up of several statements separated by semicolon (;) characters. For
example, the following stored procedure has a body made up of a BEGIN ... END block that
contains a SET statement and a REPEAT loop that itself contains another SET statement:
CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
SET @x = 0;
END;
2) Trigger Metadata
A trigger is a named database object that is associated with a table, and that activates when a
particular event occurs for the table. Some uses for triggers are to perform checks of values to be
inserted into a table or to perform calculations on values involved in an update.
A trigger is defined to activate when a statement inserts, updates, or deletes rows in the associated
table. These row operations are trigger events. For example, rows can be inserted by INSERT or
LOAD DATA statements, and an insert trigger activates for each inserted row. A trigger can be set
to activate either before or after the trigger event. For example, you can have a trigger activate
before each row that is inserted into a table or after each row that is updated.
Trigger Metadata
View Syntax
The CREATE VIEW statement creates a new view (see Section 13.1.20, “CREATE VIEW Syntax”).
To alter the definition of a view or drop a view, use ALTER VIEW (see Section 13.1.9, “ALTER
VIEW Syntax”), or DROP VIEW (see Section 13.1.31, “DROP VIEW Syntax”).
A view can be created from many kinds of SELECT statements. It can refer to base tables or other
views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any tables.
The following example defines a view that selects two columns from another table, as well as an
expression calculated from those columns:
mysql> CREATE TABLE t (qty INT, price INT);
mysql> INSERT INTO t VALUES(3, 50), (5, 60);
+------+-------+-------+
+------+-------+-------+
| 3| 50 | 150 |
| 5| 60 | 300 |
+------+-------+-------+
+------+-------+-------+
+------+-------+-------+
| 5| 60 | 300 |
+------+-------+-------+
2) DISTINCT
3) GROUP BY
4) HAVING
9) Subquery in the WHERE clause that refers to a table in the FROM clause
10) Refers only to literal values (in this case, there is no underlying table to update)
Polling
Poll Result: