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

Mysql your visual blueprint for creating open source databases- P4 docx

20 272 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 596,2 KB

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

Nội dung

Example: CREATE TABLE MailList2 name VARCHAR80 PRIMARY KEY, address VARCHAR120, city VARCHAR50, state VARCHAR2, postal VARCHAR5, INDEX postal ; MANAGE DATABASES AND TABLES 2... In this

Trang 1

■ The MySQL monitor

prompts for another line

›Type url VARCHAR(255),

and press Enter

ˇType description TEXT );

and press Enter

Note: If you want to add additional fields, include them before the closing parenthesis

■ The table is now created.

ÁTo verify that the command worked, type

SHOW COLUMNS FROM links;

and press Enter

■ The columns you created for this table are displayed

If you are not sure what length to use for a CHARor VARCHARcolumn, specify a value large enough to store a typical value You can always change the length later You can also change VARCHARcolumns to

TEXTcolumns without losing data This is explained in Chapter 3.

The MySQL server may automatically change the type of some of your columns if there is a conflict between them In particular, if you use fixed-length CHARcolumns and at least one variable-length VARCHAR

or TEXTcolumn, the entire row must be variable length, so your CHAR

columns are converted to VARCHAR.

In addition, the server automatically changes VARCHARcolumns with

a length of one to three characters to CHARcolumns, because it is not practical to use variable length when the column is this small.

While it is important to choose the correct column types when you create a table, after you have created it, you can work with VARCHAR

and CHARcolumns in exactly the same ways.TEXTcolumns also work

in most of the same ways, except that you cannot use the entire body

of a TEXTfield as an index.

MANAGE DATABASES AND TABLES 2

Trang 2

⁄From the MySQL monitor,

type USE testdb; and press

Enter

■ The database is now

selected

Note: If you did not create the testdb

database in Chapter 1, you need to

create it first

¤Type CREATE TABLE music (

and press Enter

■ This starts the table definition

■ The MySQL monitor prompts for the next line

‹Type title VARCHAR(100),

and press Enter

Sets and enumerations are different from normal text

columns in that they are limited to a specific list of

values You can use these columns whenever you

need to assign categories to the items in a table For

example, suppose you were using a database table to

catalog music recordings You could use a SETcolumn to

store the category of music that each recording contains:

category SET("rock", "pop", "blues",

"country", "dance")

The one potential disadvantage of a SETcolumn is that

each item can have only one value Anything that fits more

than one category could only be listed in one This is where

ENUMcolumns are useful.

With an ENUMcolumn, each item can be assigned any

number of values from the list you specify when you create

the table You can look at an ENUMcolumn as a list of flags, each of which can be assigned or not assigned to an item.

In the music catalog example, an ENUMcolumn would be ideal to store the media the music is available on:

media ENUM("CD","DVD","LP","Cassette")

Although you could use separate columns to achieve the same effect,ENUMcolumns are convenient because they can be assigned values as a single unit They are also stored

on the server in a highly efficient way, using only one bit per item, and are thus especially useful when you are storing many rows of data in a table.

Because ENUMand SETcolumns can have a large number

of possible values, you may need to split the column specification into two or more lines when you create the table.

USING SETS AND ENUMERATIONS

48

USING SETS AND ENUMERATIONS

Trang 3

›Type category SET("rock",

"pop", and press Enter

ˇType "blues", "country",

"dance"), and press Enter

■ These two lines define a SET column

ÁType media ENUM("CD","DVD",

and press Enter

‡Type "LP","Cassette") );

and press Enter

■ This completes the definition for the ENUM column and the CREATE TABLE command The table

is now created

The values for an ENUMcolumn are actually stored as integers A value

of 1 represents the first possible value, 2 represents the second possible value, and so on.ENUMcolumns can have a maximum of 65,535 total values available.ENUMvalues use one byte of storage if there are less than 256 possible values and two bytes if there are 256

or more.

The values for a SETcolumn are stored using individual bits This means that one byte, or eight bits, of storage is required for every eight members of the set A SETcolumn can have a maximum of 64 members, which requires eight bytes of storage.

You can change the definition for a SETor ENUMcolumn using the

ALTER TABLEquery in MySQL, described in Chapter 3 However, changing the definition does not change the values stored for existing data If you add a value at the beginning of the list, the numeric values for the entire list will change You can safely add values at the end of the list, but the best strategy is to determine the possible values in advance and include them when you first create the table.

MANAGE DATABASES AND TABLES 2

Trang 4

⁄From the MySQL monitor,

type USE testdb; and press

Enter

■ This selects the testdb database

¤Type CREATE TABLE MailList ( and press Enter

■ The MySQL monitor prompts for the next line

‹Type name VARCHAR(80) PRIMARY KEY, and press Enter

■ This defines the name field

as the primary key

Along with the various columns the table will contain,

you can specify a primary key and one or more

indexed columns In general, you will want to have at

least a primary key for any table If there is no primary key,

there may be no way to uniquely identify a single record.

This makes it impossible to edit or delete a single row

without affecting other rows in the table.

For the primary key, you should choose a column that will

have a unique value for each row of the table For example,

for a table that stores a list of names and mailing addresses,

the name field is usually a good primary key, assuming that

the list is small enough that duplicate names is not a

concern.

You can define the primary key by including the keywords

PRIMARY KEYwith one of the column definitions when you create the table, or with a separate PRIMARY KEYdefinition that specifies a column for the key in parentheses In this case, you can also use multiple fields as a primary key The following CREATE TABLEquery creates a MailList table with columns for the name, address, city, state, and postal code The name column is defined as the primary key.

CREATE TABLE MailList ( name VARCHAR(80) PRIMARY KEY, address VARCHAR(120),

city VARCHAR(50), state VARCHAR(2), postal VARCHAR(5) );

CREATE AN INDEXED TABLE

50

CREATE AN INDEXED TABLE

Trang 5

›Type address

VARCHAR(120), and

press Enter

ˇType city VARCHAR(50),

and press Enter

ÁType state VARCHAR(2),

and press Enter

‡Type postal VARCHAR(5) );

and press Enter

■ This completes the query, and the table is created

°Type SHOW COLUMNS FROM MailList; and press Enter

■ The columns for the table you created are displayed

Along with the primary key, one or more additional indexes are often useful You should only define an index on an additional column if you frequently need to search for values in that column You can add an index with the INDEX

keyword, and optionally specify the UNIQUE

keyword to require a unique value for each row.

The following example shows an expanded mailing list table with an index on the postal code field In this case, the UNIQUEkeyword is not used because multiple records can have the same code.

Example:

CREATE TABLE MailList2 ( name VARCHAR(80) PRIMARY KEY, address VARCHAR(120),

city VARCHAR(50), state VARCHAR(2), postal VARCHAR(5), INDEX (postal) );

MANAGE DATABASES AND TABLES 2

Trang 6

⁄From the MySQL monitor,

type USE testdb; and press

Enter

■ This selects the database.

Note: This task uses the prices table created earlier in this chapter

¤Type DROP TABLE prices;

and press Enter

■ The table is deleted.

‹Type SHOW TABLES; and press Enter

■ Verify that the deleted table is not listed

If you no longer have any use for a table, you can delete

it using the DROP TABLEcommand This command

immediately deletes the table, including all data You

can specify more than one table to drop with DROP TABLE,

separated by commas The following command deletes

the prices table:

DROP TABLE prices;

When you attempt to drop a table that does not exist,

MySQL returns an error You can optionally specify the IF

EXISTSkeywords to prevent the error The following

example deletes the test1 table only if it exists:

DROP TABLE IF EXISTS test1;

If you want to delete an entire database, you can use the

DROP DATABASEcommand This command deletes the

entire database including all tables and data As with DROP

TABLE, you can use the IF EXISTSkeyword to prevent an

error if the database does not exist The following

command deletes a database called newdb:

DROP DATABASE newdb;

The DROPcommand does not prompt you for confirmation, whether you are deleting a table or an entire database After you have issued the DROPcommand, there is no way to recover the data unless you have a backup copy.

Be sure that you have a backup before you use the DROP

command.

In order to drop a database or table, the MySQL username you are using must have the correct privileges Only the

rootuser is allowed to delete databases by default See Chapter 11 for more information about MySQL security.

In this example you delete the prices table and the newdb database, which you created in the sections "Create a Database" and "Create a Simple Table," earlier in this chapter Be sure you specify the names correctly to avoid deleting the wrong data.

DELETE TABLES AND DATABASES

52

DELETE A TABLE

Trang 7

The DROP TABLEcommand deletes the disk files that MySQL uses to store a table's data There are typically three separate files for each table The DROP DATABASEcommand deletes the files for each table

in the database and additionally deletes the directory for the database.

If non-MySQL files are also in this directory, it may prevent the directory from being entirely deleted.

Because the DROPcommand is drastic, be sure you have a backup of all data before deleting a table or database You will learn more about backing up MySQL databases in Chapter 8.

If you are unsure whether to delete a table, you can use the SHOW COLUMNScommand to display the columns of the table.

Example:

SHOW COLUMNS FROM tablename;

You can also use a SELECTquery to display the data in the table before deleting it The following command displays all of the rows of a table.

Example:

SELECT * FROM tablename;

DELETE A DATABASE

⁄From the MySQL monitor,

type DROP DATABASE newdb;

and press Enter

■ The database is deleted. ¤Type SHOW DATABASES;

and press Enter

■ The list of databases is displayed Verify that the database has been deleted

MANAGE DATABASES AND TABLES 2

Trang 8

When you create a table with the CREATE TABLE

command in MySQL, you specify the column definitions and other options If you later decide

to change any aspect of the table's definition, you can do so

using the ALTER TABLEcommand This command allows you to change column names, column types, and other aspects of a table's definition.

USING ALTER TABLE QUERIES

54

Basic ALTER TABLE Syntax

You can make any number of changes with a single

ALTER TABLE command You can use a variety of

commands within ALTER TABLEto add columns,

remove columns, and make other changes If you use

multiple keywords to make changes, separate them

with commas.

Example:

ALTER TABLE address

ADD COLUMN lastvisit DATE,

DROP COLUMN postal;

ADD COLUMN

Use the ADD COLUMNcommand to add a column to the

table Specify the new column name, the column type,

and any attributes You can use the same syntax as you

use when creating a table, as described in Chapter 2.

You can optionally specify the keyword FIRSTafter

ADD COLUMNto add the column at the beginning of the

table, or the AFTERkeyword and a column name to

add it after an existing column If you do not specify

either of these, the column is added at the end of the

table.

DROP COLUMN

The DROP COLUMN command enables you to delete an

existing table column Use this command with caution,

because it deletes all of the data stored in that column

in existing table rows without asking for confirmation.

To use DROP COLUMN, simply specify the column name.

CHANGE

The CHANGEcommand changes the definition of an existing column To use this command, specify the old column name followed by the new name, the column type, and any options such as DEFAULTor NULL Specify the old name twice if you are not renaming the column.

The MySQL server attempts to convert any existing data

in the column to the new column type However, in some cases, such as when you change the length of a

VARCHARcolumn to a smaller amount, the data in the column will be truncated and cannot be restored.

Example:

ALTER TABLE address CHANGE name name CHAR(120) NOT NULL;

MODIFY

The MODIFYcommand changes the definition for a column without changing its name To use this command, specify the column name, the new column type, and any options As with CHANGE, the data is converted wherever possible to the new format.

Example:

ALTER TABLE address MODIFY name CHAR(120) NOT NULL;

Trang 9

MODIFY TABLES 3

ADD INDEX

Use the ADD INDEXcommand to add an index to the

table for an existing column To use this command,

specify an optional index name followed by the

column or columns to index in parentheses If you

useADD UNIQUEinstead of ADD INDEX, a unique

index is created Before adding a unique index, be

sure the existing rows of the table have unique

values for the column or columns you plan to index.

Example:

ALTER TABLE address

ADD INDEX postindex (postal);

DROP INDEX

The DROP INDEXcommand deletes an existing index.

To use this command, specify the index name The index

name is the column name by default, or the name you

specified when creating the index.

Example:

ALTER TABLE address

DROP INDEX postindex;

ADD PRIMARY KEY

The ADD PRIMARY KEYcommand adds a primary key.

This can only be used if the table does not have an

existing primary key To use this command, specify

one or more columns to act as the primary key Each

existing row of the table must have a unique value for

the column or columns specified The column you

specify must also have the NOT NULLattribute You

can alter the column to add this attribute if necessary,

as described earlier in this section.

Example:

ALTER TABLE address

ADD PRIMARY KEY (name, address);

DROP PRIMARY KEY

The DROP PRIMARY KEYcommand removes an existing primary key This only removes the indexing information, not the column or columns that act as the key This command does not require any parameters.

Example:

ALTER TABLE address DROP PRIMARY KEY;

RENAME

The RENAMEcommand renames an existing table To use this command, specify the existing table name and the new name You can use RENAME TOas a synonym for RENAME.

Example:

ALTER TABLE temp RENAME TO temp2;

Table Options

You can change table options using an ALTER TABLE

command These options include TYPE, the table type,

COMMENT, the optional comment field, and other options The complete list of options is in Chapter 2.

To change options, specify each option followed by an equal sign and the new value.

Example:

ALTER TABLE temp TYPE=Heap, COMMENT="I changed the table type.";

ORDER BY

The ORDER BYcommand sorts the existing data in a table by the value of a specified column While you can retrieve the rows of the table in any order, this command

is useful to make the order permanent when the table is rarely changed and usually retrieved in a particular order.

Example:

ALTER TABLE address ORDER BY name;

Trang 10

Note: This example uses the testdb

database and the address table If

you have not created these, follow

the instructions in Chapter 1 or on

the CD-ROM

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

■ The database is now selected

¤Type SHOW COLUMNS FROM address; and press Enter

■ The current list of columns

is displayed

If you have created a few tables in MySQL, you learned

that there are many decisions to be made — the

columns to include, their types, and other aspects of the

table Fortunately, you can change most of these after the

table is created with the ALTER TABLEcommand.

You can use ALTER TABLE ADD COLUMNto add a column

to an existing table The basic query syntax specifies the

table, the name of the new column, and its column type:

ALTER TABLE address ADD COLUMN

country VARCHAR(10);

You can optionally specify where the new column should

be added Either specify the keyword FIRSTto insert the

new column as the first column in the table's definition, or

specify the AFTERkeyword followed by the name of an

existing column The following example adds a country

column to the address table after the existing state column:

ALTER TABLE address ADD COLUMN country VARCHAR(10) AFTER state;

When you add a column, you can specify the same attributes that you use when creating a table, as described

in Chapter 2 You can specify the column's type and display width, select a default value for the column, and specify whether null values are allowed.

You cannot specify values for the data in the table's rows for the new column The default value of the column will be used for all rows of the table until you change the data.

Be sure the new column's name does not conflict with other columns in the table The column must also be compatible with the existing columns: In particular, if there are existing variable-length text columns, such as VARCHAR

or TEXT, you cannot add a fixed-length CHARcolumn.

ADD A COLUMN TO A TABLE

56

ADD A COLUMN TO A TABLE

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

TỪ KHÓA LIÊN QUAN