By Russell Dyer
Price: $34.99 USD
£21.99 GBP
Cover | Table of Contents | Colophon
mysqld_safe script is the most common way to start
mysqld, because the script can restart the daemon if
it crashes. This helps ensure minimal downtime for database services. The
script mysqld_multi is used to start multiple sessions
of mysqld_safe, and thereby multiple
mysqld instances, for handling requests from
different ports, and to make it easier to serve different sets of
databases or to test different versions of MySQL.mysqlaccess is used for creating user accounts and setting their privileges. mysqladmin can be used to manage the MySQL
server itself from the command line. This interaction includes checking a
server’s status and usage, and shutting down a server.
mysqlshow may be used to examine a server’s status, as
well as information about databases and tables. Some of these utilities
require Perl, or ActivePerl for Windows, to be installed on the server.
See to download and install a
copy of Perl on non-Windows systems, and see to download
and install a copy of ActivePerl on Windows .mysqldump is
the most popular for exporting data and table structures to
a plain-text file known as a dump file. This can be
used for backing up data or for manually moving it between servers. The
gunzip, GNU tar, GNU gcc (at least version 2.95.2), and
GNU make. These tools are usually included in all Linux
systems and in most Unix systems. If your system doesn’t have them, you
can download them from the GNU Project’s site ().groupadd mysql useradd -g mysql mysql tar xvfz /tmp/mysql-version.tar.gz cd mysql-version
mysql. The second creates the
system user mysql and adds it to the group
mysql at the same time. The next command uses the
tar utility (along with gunzip via
the z option) to unzip and unpack the source
distribution file you downloaded. You should replace the word
version with the version number—that is to say,
you should use the actual path and filename of the installation file that
you downloaded for the second argument of the tar
command. The last command changes to the directory created by
tar in the previous line. That directory contains the
files needed to configure MySQL.--prefix option with a value set to equal the desired
directory. To set the Unix socket file’s path, you can use
--with-unix-socket-path. If you would like to use a
different character set from the default of
tar
and GNU gunzip to be able to unpack the installation
files. These tools are usually included on all Linux systems and most Unix
systems. If your system doesn’t have them, though, you can download them
from the GNU Project’s site ().groupadd mysql
useradd -g mysql mysql
cd /usr/local
tar xvfz /tmp/mysql-version.tar.gztar utility (along
with gunzip via the z option) to
unzip and unpack the source distribution file that you downloaded. The
word version in the name of the installation
file is replaced with the version number—that is to say, use the actual
path and name of the installation file that you downloaded as the second
argument of the tar command. For Sun Solaris systems, you should use gtar
instead of tar.ln -s /usr/local/mysql-version /usr/local/mysqlrpm -ivh MySQL-server-version.rpm \ MySQL-client-version.rpm
i option in the
example with an uppercase U.mysqladmin -u root shutdown
mysqladmin -u root shutdown
SEARCH ADD SYS:MYSQL\BIN
.\scripts\mysql_install_db
mysql_install_db utility is a script provided with the distribution to generate the
initial privileges or grant tables (i.e., the
mysql database). Once this is done, MySQL is ready to
be started. To do this, just enter the following from the server
console:mysqld_safe
SEARCH ADD SYS:MYSQL\BIN MYSQLD_SAFE --autoclose --skip-external-locking
mysqld -remove
msyqladmin -u root shutdown
[mysqld]. Under this heading, you could add something
like log = /var/log/mysql to enable logging and to set
the directory for the log files to the one given. You can list many
options in the file for a particular group. For a complete listing and
explanation of these options, see .mysql -u root -p
whereis mysql. Windows, Macintosh, and other GUI-type
systems have a program location utility for finding a program. If you used
the default installation method, the mysql program
probably resides at /usr/local/mysql/bin/mysql. On
Unix systems, if /usr/local/mysql/bin/ is in your
default path (the PATH environment variable), you
can specify mysql without the full pathname. If the
directory is not in your path, you can add it by entering:PATH=$PATH:/usr/local/mysql/bin export PATH
mysql -h host -u user -p
whereis mysql. Windows, Macintosh, and other GUI-type
systems have a program location utility for finding a program. If you used
the default installation method, the mysql program
probably resides at /usr/local/mysql/bin/mysql. On
Unix systems, if /usr/local/mysql/bin/ is in your
default path (the PATH environment variable), you
can specify mysql without the full pathname. If the
directory is not in your path, you can add it by entering:PATH=$PATH:/usr/local/mysql/bin export PATH
mysql -h host -u user -p
-h host argument.
This is because the default host is localhost, which
refers to the system you are on. In other circumstances, where your
commands actually have to travel over a network to reach the server,
replace the argument host
with either a hostname that is translatable to an IP address or the actual
IP address of the MySQL server. You should replace the argument
user with your MySQL
username. This is not necessarily the same as your filesystem
username.-p option instructs
CREATE DATABASE bookstore;
bookstore. You may have noticed that the commands or
reserved words are printed here in uppercase letters. This isn’t
necessary; MySQL is case-insensitive with regard to reserved words for SQL
statements and clauses. Database and table names are case-sensitive on
operating systems that are case-sensitive, such as Linux systems, but not
on systems that are case-insensitive, such as Windows. As a general
convention, though, reserved words in SQL documentation are presented in
uppercase letters and database names, table names, and column names in
lowercase letters. You may have also noticed that the SQL statement shown
ends with a semicolon. An SQL statement may be entered over more than one
line, and it’s not until the semicolon is entered that the client sends
the statement to the server to read and process it. To cancel an SQL
statement once it’s started, enter \c instead of a
semicolon.USE bookstore
USE
statement because it’s a client-based SQL .CREATE TABLE books ( book_id INT, title VARCHAR(50), author VARCHAR(50));
books with three
columns. Note that the entire list of columns is contained within
parentheses.SHOW DATABASES statement:SHOW DATABASES; +-----------+ | Database | +-----------+ | bookstore | | mysql | | test | +-----------+
SHOW
DATABASES statement lists not only the database we’ve
created, but also two others. One is the mysql
database, which contains data about user privileges and was covered in
. The third database is the
test database, which is set up by default when MySQL is
installed. It’s there as a convenience for you to be able to add tables or
run SQL statements for testing.bookstore database, once we
select the bookstore database with the
USE statement shown earlier, we would enter the
following statement:SHOW TABLES; +---------------------+ | Tables_in_bookstore | +---------------------+ | authors | | books | +---------------------+
SHOW TABLES
statement provides a list containing our two tables, just as we expected.
If you want to see a list of tables from another database while still
using the bookstore database, add a
FROM clause to the previous statement:SHOW TABLES FROM mysql;
mysql
database, even though the default database for the client session is the
bookstore database.INSERT . With the
INSERT
we can add one or more records. Before adding information about a book to
our books table, because it refers to a field in our
authors table, we need to add the author’s information
to the latter. We’ll do this by entering these SQL statements through the
mysql client:INSERT INTO authors
(author_last, author_first, country)
VALUES('Greene','Graham','United Kingdom');
SELECT LAST_INSERT_ID( );
+-------------------+
| LAST_INSERT_ID( ) |
+-------------------+
| 1 |
+-------------------+
INSERT INTO books
(title, author_id, isbn, genre, pub_year)
VALUES('The End of the Affair', 1,'0099478447','novel','1951');INSERT syntax names the columns for which the values
are to be inserted, as we’re doing here. If you’re going to enter values
for all of the columns, you don’t need to name the columns, but you must
list the data in the same order in which the columns are listed in the
table.LAST_INSERT_ID( ) function. We
could just as easily have entered SELECT author_id FROM
authors;.SELECT statement to select the data
that we want. To get all of the columns and rows from the
books table, enter the following:SELECT * FROM books;
books table. To select specific
columns, we name the columns we want. To select specific rows, we add
a WHERE clause to the end of the SELECT
statement:SELECT book_id, title, description FROM books WHERE genre = 'novel';
books table for all books where the
genre column has a value of novel.
The results will be more meaningful, of course, when we have data on more
books in the database. So, let’s assume that we’ve entered data for a few
dozen more books, and proceed.books table to
the authors table. We can join the two tables with
a JOIN clause like this:SELECT book_id, title, pub_year, CONCAT(author_first, ' ', author_last) AS author FROM books JOIN authors USING(author_id) WHERE author_last = 'Greene';
FROM clause, we join the books table to the
authors table using the author_id
columns in both tables. If the columns had different labels, we would have
to use a different clause or method in the JOIN clause
to join the tables (e.g., ON (author_id = writer_id)).
Notice in the second line of this SQL statement that we’ve employed a
string function, CONCAT( ). With this
function you can take bits of data and merge them together with text to
form more desirable-looking output. In this case, we’re taking the
author’s first name and pasting a space (in quotes) onto the end of it,
followed by the author’s last name. The results will appear in the output
display as one column, which we’ve given a column heading of
ORDER BY clause. Suppose that we want
a list of plays written by William Shakespeare from our database. We could
enter the following SQL statement to retrieve such a list and to sort the
data by the play title:SELECT book_id, title, publisher FROM books JOIN authors USING(author_id) JOIN publishers USING(publisher_id) WHERE author_last = 'Shakespeare' AND genre = 'play' ORDER BY title, pub_year;
ORDER BY clause comes at the end, after
the WHERE clause. Here the ORDER
BY clause orders the data results first by the
title column and then, within title,
by the pub_year column, or the year that the particular
printing of the play was published. By default, data is sorted in
ascending alphanumeric order. If we want to order the results in
descending order for the titles, we can just add a DESC flag immediately after the
title column in the ORDER BY clause
and before the comma that precedes pub_year:... ORDER BY title DESC, pub_year;
LIMIT clause to the end of the previous
SQL statement:SELECT book_id, title, publisher FROM books JOIN authors USING(author_id) JOIN publishers USING(publisher_id) WHERE author_last = 'Shakespeare' AND genre = 'play' ORDER BY title DESC, pub_year LIMIT 20;
ORDER BY clause. If we
want to retrieve the next 10, we would adjust the LIMIT
clause to specify the number of rows to skip, along with the number of
records to retrieve. So if we want to skip the first 20 rows and list the
next 10 rows from our sort, we replace the LIMIT clause
in the SQL statement with this one:SELECT statement containing a
COUNT( ) function
like this:SELECT COUNT(*) FROM books JOIN authors USING(author_id) WHERE author_last = 'Tolstoy'; +----------+ | COUNT(*) | +----------+ | 12 | +----------+
orders that contains information
on customer orders. We can query that table to find the total sales of a
particular book. For instance, to find the total revenues generated from,
say, William Boyd’s book Armadillo, we would enter
the following SQL statement in the mysql
client:SELECT SUM(sale_amount) AS 'Armadillo Sales' FROM orders JOIN books USING(book_id) JOIN authors USING(author_id) WHERE title = 'Armadillo' AND author_last = 'Boyd'; +-----------------+ | Armadillo Sales | +-----------------+ | 250.25 | +-----------------+
sale_amount
column from each row in the orders table that matches
the criteria of the WHERE clause. Then it adds those
numbers and displays the sum with the column heading given.orders table the date
that a customer made a particular purchase, based on his receipt number
(e.g., 1250), which in turn is the record identification number, or
sale_id. We could simply enter the following statement
and get the default format as shown in the last line of results:SELECT purchase_date AS 'Purchase Date' FROM orders WHERE sale_id = '1250'; +---------------+ | Purchase Date | +---------------+ | 2004-03-01 | +---------------+
UPDATE statement. With this
statement, you can change data for all rows or for specific records based
on a WHERE clause.UPDATE books SET pub_year = '1938' WHERE book_id = '2'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
SET keyword with the column to change and
its corresponding new value. If we wanted to change the values of more
than one column, we would provide a comma- list of each column along with the
equals sign operator and the new respective values. SET
is given only once.WHERE clause limiting the rows that
will be updated by specifying a condition the row must meet. In this case,
our condition is for a specific value of a unique column, so only one row
will be changed. The results of the query show that one row was affected,
one row was matched, one row was changed, and there were no problems to
generate warnings.books table
and one of the books is already in the table. If we use INSERT, a duplicate row will
generally be rejected. To prevent this, we can use the
REPLACE statement, which inserts rows that are new and
replaces existing rows with new data.book_id
column is assigned automatically, it’s unlikely that we would duplicate
it, because we wouldn’t tend to assign its value when adding records.
What’s unique about each book in the book business is its ISBN number,
which is the bar code number on the back of the book. To ensure that we do
not have rows with the same ISBN number, we’ll alter our
DELETE statement. For example, if we want to delete all
rows of data from our books table for the author J. K.
Rowling, because we’ve decided not to carry Harry Potter books, we could
issue the following statement:DELETE FROM books
WHERE author_id =
(SELECT authors.author_id FROM authors
WHERE author_last = 'Rowling'
AND author_first = 'J. K.');
DELETE FROM authors
WHERE author_last = 'Rowling'
AND author_first = 'J. K.';books
table where the author identification number is whatever is selected from
the authors table based on the specified author’s last
name and first name. That is to say, the author_id must
be whatever value is returned by the SELECT statement, the subquery
contained in the parentheses. This statement involves a subquery, so it
requires version 4.1 or later of MySQL. To delete these same rows with an
earlier version of MySQL, you would need to run the
SELECT statement shown in parentheses here separately
(not as a subquery), make note of the author’s identification number, and
then run the first DELETE statement, manually entering
the identification number at the end instead of the parenthetical
SELECT statement shown.SET @potter =
(SELECT author_id FROM authors
WHERE author_last = 'Rowling'
AND author_first = 'J. K.');
DELETE FROM books
WHERE author_id = @potter;
DELETE FROM authors
WHERE author_id = @potter;SET statement to establish a
variable called @potter that will contain the results
of the SELECT statement that follows in parentheses,
another subquery. Incidentally, although this subquery is not available
before version 4.1, user-defined variables are. The second SQL statement deletes
the rows from books where the author identification
number matches the value of the temporary variable. Next, we delete the
data from the SELECT statements. Also, sometimes we don’t have the
exact or complete text for a column we’re examining. For these situations,
we can use the LIKE operator. Suppose that our
books table now has thousands of entries. Suppose
further that a customer says he’s looking for a specific book. He can’t
remember the name of the author or the title of the book, but he does
remember that the words traveler and
winter are in the title. We could enter this SQL
statement to search the database based on this minimal information:SELECT book_id, title, CONCAT(author_first, ' ', author_last) AS author FROM books JOIN authors USING(author_id) WHERE title LIKE '%traveler%' AND title LIKE '%winter%'; +---------+-----------------------------------+---------------+ | book_id | title | author | +---------+-----------------------------------+---------------+ | 1400 | If on a winter's night a traveler | Italo Calvino | +---------+-----------------------------------+---------------+
LIKE operator, we use the percent sign wildcard twice to indicate that we’re searching for all rows
in which the title column’s data contains the string
traveler with zero or more
characters before it (the preceding percent sign), and zero or more
characters after it (the terminating percent sign). Put another way, the
word traveler must be contained somewhere in the
column’s data to have a pattern match. The next par