1. Trang chủ
  2. » Công Nghệ Thông Tin

Mysql your visual blueprint for creating open source databases- P11 ppt

20 254 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 671,22 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

While MySQL will work remarkably well using thedefault settings, you can change a variety of factors to improve performance.. Some of the most important factors that affect MySQL server

Trang 1

■ The variable list is

displayed

‹Click the Exit button to

return to the administration

panel

›Click the Display status button to display detailed server status

■ The status information is displayed in a new window

ˇClick Exit to return to the administration panel

You may have noticed that there is often more than one way to achieve the same result For example, if you want to display a list of MySQL variables and their current values, you can use several commands:show variablesfrom the MySQL monitor,mysqladmin variablesfrom the command prompt, the Variables tab in WinMySQLadmin, or the Show variables button in

MySQLGUI Each of these methods of MySQL administration has its advantages and disadvantages The MySQL monitor and the mysqladminutility are available

on all operating systems and provide a consistent interface, while the

MySQLGUIand WinMySQLadminutilities provide a graphical interface with easy access to common options You can use whichever commands are available to you, and whichever you find the most comfortable to work with.

In addition to the administrative features discussed here, you can use

MySQLGUIto send queries to the MySQL server and display the results Unlike the command-line MySQL monitor,MySQLGUIincludes options to save query results to a file after you view them, and saves a list of the most recent queries for easy access.

While MySQLGUIlooks simple, keep in mind that it is every bit as powerful as the command-line utilities You can use it to delete an entire database or shut down the MySQL server Be sure to select commands carefully.

Trang 2

While MySQL will work remarkably well using the

default settings, you can change a variety of factors to improve performance Some of the

most important factors that affect MySQL server performance include the speed of the server hardware, the design of tables, and the performance of particular queries.

OPTIMIZE MYSQL

Disk Access

Disk access is usually the largest bottleneck affecting a

MySQL server Because tables are stored on disk,

virtually every MySQL operation involves disk access.

MySQL will benefit from a fast disk drive Additionally,

you may want to consider using a separate drive for

MySQL data so that other server functions do not slow

down MySQL.

Processor Speed While not as important as disk speed, the processor, or CPU, of the MySQL server comes into play when working with data that has been read from disk: A faster processor will handle MySQL queries faster It is also beneficial to analyze the other applications on the server If a Web server or other software is using the CPU intensively, MySQL would benefit from a faster processor or a dedicated MySQL server machine.

Memory

A busy MySQL server requires a large amount of

memory This is used to store data temporarily while it

is sent to clients, and for temporary tables Adding

memory will often improve performance, especially if the disk drives and CPU are already reasonably fast.

OPTIMIZE THE MYSQL SERVER

Using Fixed-Length Rows

When a table is frequently changed, MySQL performs

better using fixed-length rows To use fixed-length rows

on a table, avoid using variable-length column types

such as VARCHAR,TEXT, and BLOB The disadvantage of

fixed-length rows is that all rows take the same amount

of space Variable-length rows will make more efficient

use of disk space if there is a large amount of variation

in the sizes of data items.

Reduce Data Size The less data MySQL has to work with, the faster it will

be Use the smallest column sizes possible for your data and eliminate unnecessary columns to improve the MySQL server's performance working with a table.

OPTIMIZE TABLE DESIGN

188

One aspect of MySQL that is relatively easy to optimize is

the speed of the machine running the MySQL server.

Upgrading disks, memory, or processor, or switching to a

faster machine can dramatically improve performance.

The design of a table can also affect performance By

considering performance when you design and create a

table under MySQL, you can ensure that queries on the

table can be quickly handled by the server.

Trang 3

OPTIMIZE AND TROUBLESHOOT MYSQL 10

Using EXPLAIN

You can use the EXPLAINcommand with a SELECT

query to display information about how MySQL will

handle the query When you use EXPLAIN, the MySQL

server does not actually process the SELECTquery.

Instead, it displays a chart of information about the query.

The information displayed by EXPLAINincludes the

tables the query will use, the keys it can use to quickly

find records, the number of rows the query will return,

and any extra explanation the server can offer about the

query.

The Extra column will indicate whether a file sort is

necessary to process an ORDER BYclause It will also

indicate whether a temporary table will be needed to

handle a GROUP BYclause If either of these is present,

it indicates a major bottleneck for the query You may

be able to eliminate the problem by adding an index or

changing the query.

Example:

EXPLAIN SELECT * FROM quotes;

Improve Queries After you have isolated a slow query, you can try changing its syntax Eliminate any unnecessary ORDER

BY clauses, as they can slow down the query Add

WHEREclauses to target specific records wherever possible, and use the LIMITclause to limit the number

of records returned See Chapter 6 for details about the syntax of these SELECTquery clauses.

Add Indexes

If you frequently search for values in a particular column, you may be able to improve performance by adding an index on that column You can use the ALTER TABLEcommand to add an index at any time This is explained further in "Improve Performance with Indexes," later in this chapter.

Lock Tables MySQL normally handles table locking automatically You may be able to improve the performance of a complex query or series of queries by locking the table first You can use the LOCK TABLESand UNLOCK TABLES

commands to control table locking This is described in

"Manage Table Locking," later in this chapter.

OPTIMIZE SLOW QUERIES

Multiple Tables and Relationships

Performance problems multiply when you are working

with multiple tables Because JOINqueries that retrieve

data from multiple tables tend to be slow, do not divide

data into more tables than necessary.

When you do use multiple tables that have a

relationship, be sure the columns that form the

relationship are the same type, length, and preferably

have the same name This will ensure that the MySQL

server can perform a JOINquery efficiently.

Sort Table Data You can use the ORDER BYkeywords with an ALTER TABLEcommand to sort the data in the table This can improve performance when the contents of the table are often read in the same order, and are not changed frequently.

Example:

ALTER TABLE address ORDER BY name;

OPTIMIZE TABLE DESIGN (CONTINUED)

Often, a particular query that is used frequently can slow

down the MySQL server By optimizing a query's syntax,

you can often improve its performance.

The MySQL server keeps track of the number of slow

queries, or queries that took more than a certain length

of time, since the server started You can display this

value using the SHOW STATUScommand in the MySQL

monitor or the mysqladmin statuscommand at the command prompt.

The MySQL server can optionally maintain a slow query log, which keeps a record of each slow query This is particularly useful for determining which queries are slowing down the server This log file is described in detail in "View MySQL Log Files," later in this chapter.

Trang 4

⁄From the command

prompt, type cd /usr/local/

mysql/data/testdb and press

Enter

■ This switches to the directory where the testdb database is stored

Note: On Windows systems, the directory is usually c:\mysql\data\testdb

¤Type myisamchk quotes and press Enter

■ This checks the table for errors and displays a report

Note: To check a different table, replace quotes with the name of the table

MySQL includes a utility called myisamchkthat

allows you to check tables for errors and repair any errors that occur You can use this utility as a regular check to watch for errors, or when you suspect a

problem with a table This utility is for the default MyISAM

table type An older utility,isamchk, works for ISAM tables.

To check a table for errors, start in the directory where the

database files are stored, typically /usr/local/mysql/data/

database_name Type myisamchkfollowed by one or more

table names The check will be performed immediately, and

may take several minutes on a large table No clients can

access the table while myisamchkis running, and

myisamchkonly works if no clients have a lock on the

table The following example checks the quotes table:

cd /usr/local/mysql/data/testdb

myisamchk quotes

The myisamchkutility displays a series of status messages during the table check If any of these indicate an error

in the table, you can attempt to repair the table Use the

myisamchk -roption to attempt to repair a corrupt table The following example repairs the quotes table:

myisamchk -r quotes

If an error message is displayed, and myisamchkis unable

to repair the table using this option, you can try the -o

option This performs a slower recovery process that may work when the standard process fails.

Unlike other MySQL utilities, the myisamchkutility does not require a MySQL username and password It works directly with database files For this reason, in the default installation, your UNIX username must have root access to run myisamchk On Windows systems, this utility is available as c:\mysql\bin\myisamchk.exe.

CHECK A TABLE FOR ERRORS

190

CHECK A TABLE FOR ERRORS

Trang 5

‹Type myisamchk -m quotes

and press Enter

■ This performs a more detailed (medium) check on the table

›Type myisamchk -r quotes and press Enter

■ This attempts to recover the table data

The myisamchkutility includes a number of additional options to control the check and repair process Type myisamchk helpfor a complete list

of options The following table describes some of the most useful options:

OPTION DESCRIPTION

-c Check (default if no options are specified)

-e Extended check — slow but more thorough

-m Medium check — faster than extended

-F Fast check — only checks improperly closed tables

-C Checks only tables changed since the last check

-i Displays information about the table while checking

-f Automatically repairs the table if any errors are detected

-T Does not mark table as checked

-r Recover — attempts to repair table and recover data

-o Safe recover — uses slower recovery method

-q Quick recover — checks index files only

-v Verbose — displays detailed information

-V Displays the myisamchkversion number

-w Wait — waits until no clients are locking table before checking

Trang 6

Note: This example uses the quotes

table in the testdb database, but it

would work with any table

⁄From the MySQL monitor, type USE testdb; and press Enter

■ The database is now selected

¤Type OPTIMIZE TABLE

quotes; and press Enter.

■ The table is scanned and optimized, and a report is displayed

When you delete rows from a MySQL table, they

are not actually deleted Instead, MySQL marks the rows as deleted and re-uses the space later when rows are inserted If you have deleted a large number

of rows from a table, you should optimize the table to reclaim

the space Optimizing is also necessary when a table with

variable-length rows has been changed many times.

To optimize a table, use the OPTIMIZE TABLEcommand

within the MySQL monitor To use this command, specify

the table name The following example optimizes the

quotes table:

OPTIMIZE TABLE quotes;

Along with reclaiming space from deleted rows, the

OPTIMIZE TABLEcommand also repairs minor errors

in table rows, sorts the index files, and updates the table's

statistics You can use this command as often as you desire

without damaging a table However, the table is locked and

cannot be used by clients during the optimization process.

From time to time, you may run into a situation where a MySQL table becomes corrupted This usually happens when a power outage or hardware failure causes the server

to go down unexpectedly while a table is being updated In most cases, you can easily repair the table You can use the

myisamchkutility discussed earlier or the REPAIR TABLE

command to repair a damaged table.

To use REPAIR TABLE, specify the table name You can also specify the optional keyword QUICKfor a quick repair

or EXTENDEDfor an extended repair If the regular repair does not work, the extended option may The following command repairs the quotes table:

REPAIR TABLE quotes;

OPTIMIZE AND REPAIR TABLES

192

OPTIMIZE AND REPAIR TABLES

Trang 7

‹Type REPAIR TABLE

quotes; and press Enter.

■ This attempts to repair any errors in the table

›Type SELECT * FROM

quotes; and press Enter.

■ This displays the contents

of the table Verify that the table rows are undamaged

Along with OPTIMIZE TABLEand REPAIR TABLE, MySQL includes a CHECK TABLEcommand This command is equivalent to the myisamchkutility, but runs from the MySQL monitor or another client To use CHECK TABLE, specify one or more table names The following example checks the quotes table for errors:

Example:

CHECK TABLE quotes;

You can also use several optional keywords with CHECK TABLEafter the table name These are described in the table below.

QUICK Quick check — does not scan all table rows

FAST Fast check — only checks improperly closed tables

CHANGED Checks only tables that have changed since the last check

MEDIUM Medium check — checks each table row (default)

EXTENDED Extended check — comprehensive but slow on large tables

Trang 8

The MySQL server is a complex system, and includes a

number of parameters you can use to tune the

server's performance You can modify these values by

editing configuration files or with command-line options.

Each configuration file is divided into sections for different MySQL components For example, the line [mysqld]

begins the section for the server, and [client]begins the section for clients Within each section, each line can include

an option from the program's command-line options or the

set-variablecommand to set a system variable.

MYSQL CONFIGURATION OPTIONS

194

The Global Configuration File

The global configuration file is read first On UNIX

systems, this file is /etc/my.cnf On Windows systems,

the two global files are supported: my.ini in the

Windows system directory, and my.cnf in the root

directory, typically C:\.

The User Configuration File

On UNIX systems, each user can have their own

configuration file, my.cnf, in their home directory You

can use this file to set values for each user, typically for

MySQL client utilities.

The Server Configuration File The server configuration file affects a particular copy of the MySQL server software, and is only needed when multiple servers are installed on the same machine This file also has the filename my.cnf On UNIX systems, it is stored in the data directory under the MySQL

installation, typically /usr/local/mysql/data On Windows systems, the file is usually under C:\mysql\data\ The values you specify in the server configuration file override the values in the global file CONFIGURATION FILES

The [client]section in the configuration file includes

options that affect all of the MySQL client programs,

including the MySQL monitor,mysql, the mysqladmin

utility,myisamchk, and other client tools This section

is particularly useful in a my.cnf file in a user's home

directory For example, the following file excerpt sets

the passwordoption for MySQL clients If you include

this in the my.cnf file in your home directory, you do

not need to specify a password when using MySQL

client programs.

[client]

password=mypassword

The table below lists several options that may also be useful in the [client]section for a particular user.

host=name Specifies a MySQL server to

connect to

user=name Username for the MySQL server,

if different from UNIX username

password=value Password for the MySQL server

database=value Default database to select

CLIENT OPTIONS

MySQL supports a variety of configuration files Each can

contain the same commands and settings, but the order

in which they are read determines which files can

override others.

Trang 9

OPTIMIZE AND TROUBLESHOOT MYSQL 10

back_log Maximum number of client requests waiting for threads

concurrent_inserts Specifies ONto allow INSERToperations while clients are reading data

connect_timeout Number of seconds the server waits for a connection before timing out

delayed_insert_limit Number of rows of an INSERT DELAYEDquery to process at a time

delayed_insert_timeout Time the server waits for additional INSERT DELAYEDitems

delayed_queue_size Number of INSERT DELAYEDrows to store

flush_time Closes all tables after the specified number of seconds

interactive_timeout Number of seconds of idle time before disconnecting interactive clients

join_buffer_size Buffer size for full joins (queries from multiple tables)

key_buffer_size Buffer size for index values

long_query_time Amount of seconds before a query is considered slow

max_allowed_packet Maximum size of a single packet of data

max_connections Maximum number of simultaneous client connections allowed

max_connect_errors Number of allowed errors before blocking connections from a host

max_delayed_threads Maximum number of threads used for INSERT DELAYEDqueries

max_join_size Maximum number of rows for JOINqueries

max_sort_length The number of bytes of each BLOBor TEXTvalue to use when sorting

max_user_connections Maximum number of connections for each username

net_buffer_length Default size for the communication buffer

net_read_timeout Number of seconds to wait before aborting when reading data

net_write_timeout Number of seconds to wait before aborting when writing data

thread_cache_size Number of threads kept standing by for use by clients

wait_timeout Number of seconds of idle time before disconnecting a client

SYSTEM VARIABLES

Set Variables

You can set MySQL system variables by

including them in the [mysqld]section

of a configuration file, using the

set-variablecommand The following

example sets the

max_allowed_packetvariable:

[mysqld]

set-variable max_allowed_packet=1M

You can also set variables using the

set-variableoption when

mysqldis started.

Display Current Values You can display the current values of all of the system variables using the

SHOW VARIABLEScommand from the MySQL monitor or the

mysqladmin variablescommand at the UNIX or Windows command prompt This is useful if you are unsure whether the configuration files are being read correctly, and is the first thing you should do if a variable change has not produced the effect you expected You can also use the LIKEoperator with SHOW VARIABLESto show a section of the list The following example shows the values of all variables that include the characters "max" in their names:

SHOW VARIABLES LIKE '%max%';

MySQL includes a number of system variables that

control the behavior of the server While these variables

have sensible default values, setting them to optimal

values for your system can dramatically improve the server's performance The table below describes key system variables for optimizing performance.

Trang 10

⁄From the MySQL monitor,

type SHOW STATUS; and

press Enter

■ The current values of the status variables are displayed

¤Type SHOW STATUS LIKE

'%Opened%'; and press Enter.

■ The variables that match the string you specified are displayed

To optimize the performance of a MySQL server,

the first step is to determine how it is currently

performing MySQL keeps a number of running

status variables that you can examine to get a snapshot of

the server's current performance This will let you know

how much traffic the server is handling, as well as early

indications of performance problems.

To display the status variables, you can use the SHOW

STATUScommand in the MySQL monitor or the

mysqladmin extended-statuscommand at the

command prompt The output of either command is a table

of variables and their values You can use the LIKEoperator

with SHOW STATUSto show only certain values.

Most of the variables count the number of times something

has happened since the server started For example, the

Opened_tablesvalue is the number of table that have

been opened, and the Questionsvalue is the number of

queries the server has received The Uptimevalue gives

you the number of seconds the server has been running, so you can use this and the various variables to get an idea of how the server performs over time.

The Threads_connectedvalue indicates how many client connections are currently open to the server, and the

Max_used_connectionsvalue is the largest number of clients that are simultaneously connected You can use these values to determine whether the server is busy and whether the max_concurrent_userssystem variable needs to be increased.

Slow_queriesis another value you should watch carefully This is the number of queries that have taken more than the expected amount of time The time for a slow query is set using the long_query_timesystem variable If many slow queries are being counted, this means the server is running slower than expected, or some particular queries in use are slowing down the server.

DISPLAY SERVER PERFORMANCE

INFORMATION

196

DISPLAY SERVER PERFORMANCE INFORMATION

Ngày đăng: 03/07/2014, 01:20