Sunday, April 20, 2008

Retrieving specific information


To retrieve specific information, list the columns containing the information you want. For example:

SELECT columnname,columnname,columnname,... FROM tablename

This query retrieves the values from all the rows for the indicated column(s). For instance, the following query retrieves all the last names and first names stored in the Member table:

SELECT lastName,firstName FROM Member

You can perform mathematical operations on columns when you select them.
For example, you can use the following SELECT query to add two columns:

SELECT col1+col2 FROM tablename

Or you could use the following query:

SELECT price,price*1.08 FROM Pet

The result is the price and the price with the sales tax of 8 percent added.
You can change the name of a column when selecting it, as follows:

SELECT price,price*1.08 AS priceWithTax FROM Pet

The AS clause tells MySQL to give the name priceWithTax to the second column retrieved. Thus, the query retrieves two columns of data: price and priceWithTax.
In some cases, you don’t want to see the values in a column, but you want to know something about the column. For instance, you might want to know the lowest value in the column or the highest value in the column. For example, the query to find out the highest price in the Pet table is

SELECT MAX(price) FROM Pet

SQL words that look like MAX() and SUM(), with parentheses following the name, are functions. Some functions provide information about a column. Other functions change each value selected. For example, SQRT() returns the square root of each value in the column, and DAYNAME() returns the name of the day of the week for each value in a date column, rather than the actual date stored in the column. More than 100 functions are available for use in a SELECT query. For descriptions of all the functions, see the MySQL online manual at dev.mysql.com/doc/refman/5.0/en/functions.html.

Tuesday, April 8, 2008

Retrieving information from database

The only purpose in storing information is to have it available when you need it. A database lives to answer questions. What pets are for sale? Who are the members? How many members live in Arkansas? Do you have an alligator for sale? How much does a dragon cost? What is Goliath Smith’s phone number? And on and on. You use the SELECT query to ask the database questions.
The simplest, basic SELECT query is

SELECT * FROM tablename

This query retrieves all the information from the table. The asterisk (*) is a wildcard meaning all the columns.
The SELECT query can be much more selective. SQL words and phrases in the SELECT query can pinpoint the information needed to answer your question. You can specify what information you want, how you want it organized, and the source of the information:
  • You can request only the information (the columns) that you need to answer your question. For instance, you can request only the first and last names to create a list of members.
  • You can request information in a particular order. For instance, you can request that the information be sorted in alphabetical order.
  • You can request information from selected objects (the rows) in your table. For instance, you can request the first and last names for only those members whose addresses are in Florida.
In MySQL 4.1, MySQL added the ability to nest a SELECT query inside another query. The nested query is called a subquery. You can use a subquery in SELECT, INSERT, UPDATE, or DELETE queries or in SET clauses. A subquery can return a single value, a single row or column, or a table, which is used in the outer query. All the features of SELECT queries can be used in subqueries. See the MySQL online manual at dev.mysql.com/doc/refman/5.0/en/ subqueries.html for detailed information on using subqueries.

How to adding a bunch of data into database?

If you have a large amount of data to enter and it’s already in a computer file, you can transfer the data from the existing computer file to your MySQL database. The SQL query that reads data from a text file is LOAD. The LOAD query requires you to specify a database.

Because data in a database is organized in rows and columns, the text file being read must indicate where the data for each column begins and ends and where the end of a row is. To indicate columns, a specific character separates the data for each column. By default, MySQL looks for a tab character to separate the fields. However, if a tab doesn’t work for your data file, you can choose a different character to separate the fields and tell MySQL in the query that a different character than the tab separates the fields. Also by default, the end of a line is expected to be the end of a row — although you can choose a character to indicate the end of a line if you need to. A data file for the Pet table might look like this:

UnicornhorseSpiral horn5000.00/pix/unicorn.jpg
PegasushorseWinged8000.00/pix/pegasus.jpg
LioncatLarge; Mane on neck2000.00/pix/lion.jpg

A data file with tabs between the fields is a tab-delimited file. Another common format is a comma-delimited file, where commas separate the fields. If your data is in another file format, you need to convert it into a delimited file. To convert data in another file format into a delimited file, check the manual for that software or talk to your local expert who understands the data’s current format. Many programs, such as Excel, Access, and Oracle, allow you to output the data into a delimited file. For a text file, you might be able to convert it to delimited format by using the search-and-replace function of an editor or word processor. For a truly troublesome file, you might need to seek the help of an expert or a programmer.
The basic form of the LOAD query is

LOAD DATA INFILE “path/datafilename” INTO TABLE tablename

The query loads data from a text file located on your server. If the filename does not include a path, MySQL looks for the data file in the directory where your table definition file, called tablename.frm, is located. By default, this file is located in a directory named for your database, such as a directory named PetDirectory. This directory is located in your data directory, which is located in the main directory where MySQL is installed. For example, if the file was named data.dat, the LOAD command might look for the file at C:\Program Files\MySQL\MySQL Server 5.0\data\PetDirectory\ data.dat.
This basic form can be followed by optional phrases if you want to change a
default delimiter. The options are

FIELDS TERMINATED BY ‘character’
FIELDS ENCLOSED BY ‘character’
LINES TERMINATED BY ‘character’

Suppose that you have the data file for the Pet table, shown previously in this section, except that the fields are separated by a comma rather than a tab. The name of the data file is pets.dat, and it’s located in the same directory as the database. The SQL query to read the data into the table is

LOAD DATA INFILE “pets.dat” INTO TABLE Pet FIELDS TERMINATED BY ‘,’

To use the LOAD DATA INFILE query, the MySQL account must have the FILE privilege on the server host.

You can also load data from a text file on your local computer by using the word LOCAL, as follows:

LOAD DATA LOCAL INFILE “path/datafilename” INTO TABLE tablename

You must include a path to the file. Use forward slashes for the path, even on a Windows computer, such as “C:/data/datafile1.txt”. If you get an error message when sending this query, LOCAL may not be enabled.

To look at the data that you loaded — to make sure that it’s correct — use an SQL query that retrieves data from the database. I describe these types of SQL queries in detail in the next section. In brief, use the following query to look at all the data in the table so that you can check it:

SELECT * FROM Pet

How to add one row at a time to a database?

You use the INSERT query to add a row to a database. This query tells MySQL which table to add the row to and what the values are for the fields in the row.
The general form of the query is

INSERT INTO tablename (columnname, columnname,...,columnname)
VALUES (value, value,...,value)

The following rules apply to the INSERT query:
  • Values must be listed in the same order in which the column names are listed. The first value in the value list is inserted into the column that’s named first in the column list; the second value in the value list is inserted into the column that’s named second; and so on.
  • A partial column list is allowed. You don’t need to list all the columns. Columns that are not listed are given their default value or left blank if no default value is defined.
  • A column list is not required. If you’re entering values for all the columns, you don’t need to list the columns at all. If no columns are listed, MySQL will look for values for all the columns, in the order in which they appear in the table.
  • The column list and value list must be the same length. If the list of columns is longer or shorter than the list of values, you get an error message like this: Column count doesn’t match value count.
The following INSERT query adds a row to the Member table:

INSERT INTO Member (loginName,createDate,password,lastName, street,city,state,zip,email,phone,fax)
VALUES (“bigguy”,”2001-Dec-2”,”secret”,”Smith”, “1234 Happy St”,”Las Vegas”,”NV”,”88888”, “gsmith@GSmithCompany.com”,”(555) 555-5555”,””)


Notice that firstName is not listed in the column name list. No value is entered into the firstName field. If firstName were defined as NOT NULL, MySQL would not allow this. Also, if the definition for firstName included a default, the default value would be entered, but because it doesn’t, the field is left empty. Notice that the value stored for fax is an empty string. To look at the data that you entered and ensure that you entered it correctly, use an SQL query that retrieves data from the database. I describe these SQL queries in detail in “Retrieving information,” later in this chapter. In brief, the following query retrieves all the data in the Member table:

SELECT * FROM Member

Friday, April 4, 2008

How to add information?

Every database needs data. For example, you might want to add data to your database so that your users can look at it. Or you might want to create an empty database for users to put data into, making the data available for your eyes only — an example of this is the Member Directory. In either scenario, data will be added to the database.
If your data is still on paper, you can enter it directly into a MySQL database, one row at a time, by using an SQL query. However, if you have a lot of data, this process could be tedious and involve a lot of typing. Suppose that you have information on 1000 products that must be added to your database. Assuming that you’re greased lightening on a keyboard and can enter a row per minute, that’s 16 hours of rapid typing — well, rapid editing, anyway. Doable, but not fun. On the other hand, suppose that you need to enter 5000 members of an organization into a database and that it takes five minutes to enter each member. Now you’re looking at more than 400 hours of typing — who has time for that?
If you have a large amount of data to enter, consider some alternatives. Sometimes scanning in the data is an option. Or perhaps you need to beg, borrow, or hire some help. In many cases, it could be faster to enter the data into a big text file than to enter each row in a separate SQL query. The SQL query LOAD can read data from a big text file (or even a small text file). So, if your data is already in a computer file, you can work with that file; you don’t need to type all the data again. Even if the data is in a format other than a text file (for example, in an Excel, Access, or Oracle file), you can usually convert the file to a big text file, which can then be read into your MySQL database. If the data isn’t yet in a computer file and there’s a lot of data, it might be faster to enter that data into the computer in a big text file and transfer it into MySQL as a second step.
Most text files can be read into MySQL, but some formats are easier than others. If you’re planning to enter the data into a big text file, read the section, “Adding a bunch of data,” to find the best format. Of course, if the data is already on the computer, you have to work with the file as it is.

How to Move Data Into and Out of the Database?


An empty database is like an empty cookie jar — it’s not much fun. And searching an empty database is no more interesting or fruitful than searching an empty cookie jar. A database is only useful with respect to the information that it holds.
A database needs to be able to receive information for storage and to deliver information on request. For instance, the MemberDirectory database needs to be able to receive the member information, and it also needs to be able to deliver its stored information when you request it. If you want to know the address of a particular member, for example, the database needs to deliver that information when you request it.
Your MySQL database responds to four types of requests:
  • Adding information: Adding a row to a table.
  • Updating information: Changing information in an existing row. This includes adding data to a blank field in an existing row.
  • Retrieving information: Looking at the data. This request does not remove data from the database.
  • Removing information: Deleting data from the database.
Sometimes your question requires information from more than one table. For instance, the question, “How much does a green dragon cost?” requires information from the Pet table and from the Color table. You can ask this question easily in a single SELECT query by combining the tables. In the following sections, I discuss how to receive and deliver information as well as how to combine tables.

Wednesday, April 2, 2008

Changing the database structure

Your database isn’t written in stone. By using the ALTER query, you can change the name of the table; add, drop, or rename a column; or change the data type or other attributes of the column.
The basic format for this query is ALTER TABLE tablename, followed by the specified changes.
  • ADD columnname definition Adds a column; definition includes the data type and optional definitions.
  • ALTER columnname SET DEFAULT value Changes the default value for a column
  • ALTER columnname DROP DEFAULT Removes the default value for a column.
  • CHANGE columnname newcolumnname definition Changes the definition of a column and renames the colum, definition includes the data type and optional definitions
  • DROP columnname Deletes a column, including all the data in the column. The data cannot be recovered.
  • MODIFY columnname definition Changes the definition of a column; definition includes the data type and optional definitions.
  • RENAME newtablename Renames a table.
Changing a database is not a rare occurrence. You might want to change your database for many reasons. For example, suppose that you defined the column lastName with VARCHAR(20) in the Member table of the MemberDirectory database. At the time, 20 characters seemed sufficient for a last name. But now you just received a memo announcing the new CEO, John Schwartzheimer-Losertman. Oops. MySQL will truncate his name to the first 20 letters, a less-than-desirable new name for the boss. So you need to make the column wider — pronto. Send this query to change the column in a second:
ALTER TABLE Member MODIFY lastName VARCHAR(50)
 
breast-cancer diabetes-informa... weight-losse lung-mesotheliom... eating-disorders medical-billing php-and-mysql skin-cancer medical-health astronomy-guide cancer-diseases health insurance seo-news-2008 forex3003 lawyer-lookingforalawyer earnmoneyonline-earn forexautotrading-forex forex-trade forextrading forex-trading-forex-trading-08 searchingforcancertreatment adsense jiankang8008 beauty-girl forex5005