Download Introduction to MySQL RDBMS

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft Access wikipedia , lookup

IMDb wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Concurrency control wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Relational algebra wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Database wikipedia , lookup

Ingres (database) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Join (SQL) wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
Introduction to MySQL RDBMS
A database is a software program which allows for storage and retrieval of information
on a computer hard drive’s file system or other device. A relational database is a
database that allows for queries which typically use Structured Query Language (SQL) to
store and retrieve data. Relational databases allow for more efficient queries which use
less CPU power and memory allocation, as they are optimized for efficiency. However,
connecting to a database is significantly slower than just reading a simple file off of your
computer’s hard drive. The added features of a relational database make this speed
decrease worthwhile in many situations.
One of the most popular databases used for dynamic web database applications is called
mySQL. It is commonly installed on popular web hosting provider’s Unix and Linux
servers. It is free and easy to use.
Data in relational databases is stored in four primary areas: databases, tables, rows, and
columns. A database is an area within the database software that contains all the tables
that make up this particular set of data.
1. One or more MySQL clients connect to one (or more) MySQL servers.
2. Each client handles work such as
o Initiating authentication, password hashing, and so forth
o Reducing text queries into more efficient tokens
o Delivering queries to the server
o Caching result sets from the server
o Managed compressed and/or encrypted connections
3. The MySQL server handles requests from clients and returns responses to them.
4. Requests are first handled by the management layer, which is the coordinator for
the MySQL server. It handles tasks such as
o Decrypting and/or decoding connections
o Validating and parsing queries
o Fetching cached queries from the query cache
o Passing instructions to the correct storage engine
5. Storage engines manage the memory and disk-level representation of databases,
tables, and indexes. Each storage engine manages different types of databases,
tables, indexes, and so on. They also manage some logs and statistics generation.
6. The management layer and the storage engines interact heavily with the memory,
the disk, and the network. The management layer writes logs to disk, stores and
reads caches in memory, reads binary logs from the network, and so on. The
storage engines store data (tables, logs, and so forth) on disk and in memory,
sends data via the network to other remote MySQL servers, and so on.
Relational Database concept
A Relational Database Management System facilitates the organization, storage, access,
security, and integrity of data and eliminates data redundancy. It stores the data in a set
of tables each of which contains a unique identifier. Typical examples of RDBMS
software include Oracle, Microsoft SQL Server, Sybase, PostgreSQL, MySQL, etc.
Table (Entity)
A database table is a collection of rows and columns which describe the necessary
structure to store data pertaining to a specific entity.
Fields (Attribute)
A field is an attribute pertaining to an entity, and it is organized as a column in a database
table.
Primary Key
A primary key is responsible for uniquely identifying a particular record belonging to a
specific entity. It is the unique identifier for each row of a database table.
Unique Key
A unique key is an attribute which is unique for that column of the table. A unique key
unlike a primary key may or may not be null. Note that a primary key or candidate key
should always be a unique key, but the reverse is not always true.
Composite Key
A candidate key is a unique identifier that enforces the rule that no tuple will be
duplicated. A Composite key is composed of a number of attributes that together
maintain the uniqueness.
Foreign Key
A foreign key is a reference to another key in a different table and is used to declare
referential integrity constraints. These are actually integrity constraints which enforce
that the principle "value of the attribute set is drawn from a candidate key in another
relation."
Data Description Language (DDL)
This is a language that is used to define data and their relationships to other data in a
database.
Data Manipulation Language (DML)
This is a 4 GL programming language that defines how to manipulate the data that is
stored in the database.
Primary Table and Related Table
Primary and related table definition is always between two tables which have a
relationship between them. For example the tables Car and CarType have a relationship.
The foreign key (model_id) of the Car table refers to the CarType table primary key
(model_id). The CarType table is the primary table and the Car table is the related table.
There is also a relation between the Car and Rent tables. The Reg_no of the Rent table
(foreign key) refers to the Reg_no of the Car table (primary key). In this case the Car
table is the primary table and the Rent table is the related table.Primary table is the table
whose primary key is referenced from another table's foreing key. The table having this
foreign key is a related table.The primary table is also called a parent table and the related
table is called a child table.
Relation
A relation is a link between two tables and is defined as a set of tuples all of which have
the same attributes. The following are the types of relations that can exist:
 One-to-many
 Many-to-many
 One-to-one
SQL (Structured Query Language)
In 1971, IBM researchers created a simple non-procedural language called Structured
English Query Language. or SEQUEL. This was based on Dr. Edgar F. (Ted) Codd's
design of a relational model for data storage where he described a universal programming
language for accessing databases.
In the late 80's ANSI and ISO (these are two organizations dealing with standards for a
wide variety of things) came out with a standardized version called Structured Query
Language or SQL. SQL is prounced as 'Sequel'. There have been several versions of SQL
and the latest one is SQL-99. Though SQL-92 is the current universally adopted standard.
SQL is the language used to query all databases. It's simple to learn and appears to do
very little but is the heart of a successful database application. Understanding SQL and
using it efficiently is highly imperative in designing an efficient database application. The
better your understanding of SQL the more versatile you'll be in getting information out
of databases.
Data Types under MySQL
Type
Size in
bytes
Description
Integer with unsigned range of 0-255 and a
signed range from -128-127
Integer with unsigned range of 0-65535 and a
SMALLINT (length)
2
signed range from -32768-32767
Integer with unsigned range of 0-16777215
MEDIUMINT(length)
3
and a signed range from -8388608-8388607
Integer with unsigned range of 0-429467295
INT(length)
4
and a signed range from -21474836482147483647
Integer with unsigned range of 018446744073709551615 and a signed range
BIGINT(length)
8
from
-92233720368547758089223372036854775807
Floating point number with max. value +/FLOAT(length, decimal)
4
3.402823466E38 and min.(non-zero) value
+/11.175494351E-38
Floating point number with max. value +/- DOUBLEPRECISION(length,
8
1.7976931348623157E308 and min. (nondecimal)
zero) value +/-2.2250738585072014E-308
Floating point number with the range of the
DECIMAL(length, decimal)
length DOUBLE type that is stored as a CHAR field
type.
YYYYMMDDHHMMSS or YYMMDDHHMMSS or
YYYYMMDD, YYMMDD. A Timestamp value is
TIMESTAMP(length)
4
updated each time the row changes value. A
NULL value sets the field to the current time.
DATE
3
YYYY-MM-DD
TIME
3
HH:MM:DD
DATETIME
8
YYYY-MM-DD HH:MM:SS
YEAR
1
YYYY or YY
A fixed length text string where fields shorter
CHAR(length)
length than the assigned length are filled with
trailing spaces.
A fixed length text string (255 Character Max)
VARCHAR(length)
length where unused trailing spaces are removed
before storing.
A text field with max. length of 255
TINYTEXT
length+1
characters.
A binary field with max. length of 255
TINYBLOB
length+1
characters.
TEXT
length+1 64Kb of text
BLOB
length+1 64Kb of data
MEDIUMTEXT
length+3 16Mb of text
MEDIUMBLOB
length+3 16 Mb of data
LONGTEXT
length+4 4GB of text
TINYINT (length)
1
LONGBLOB
ENUM
SET
length+4 4GB of data
This field can contain one of a possible 65535
1,2
number of options. Ex: ENUM('abc','def','ghi')
This type of field can contain any number of a
1-8
set of predefined possible values.
Working with MySQL command Prompt
Login
Command Prompt just type flowing command.
mysql -h host -u user –p
If this not work just set the mysql.exe path to PATH environment variable. Your default
user name is root and password is blank
Show
Show can be used to show all database tables in a particular database, or all databases in a
particular server.
Use this syntax to do so:
“show databases” or “show tables”
Describe
Describe lets you see the structure of an existing database table by typing in this syntax:
“describe tablename”
Create New Database
CREATE DATABASE <database name>;
Ex:
CREATE DATABASE CarRent;
Selecting database to work
A single installation of MySQL can have multiple databases. Any query that operates on
a database or table must have some way of knowing on which database or table to
operate.
USE <database name>;
Ex:
USE test;
Deleting a Database
DROP DATABASE <database name>;
Ex:
DROP DATABASE library;
CREATE TABLES
CREATE TABLE <tbl_name>
(create_definition,...)
[table_option] ...
Ex:
CREATE TABLE names (
contact_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName CHAR(20),
LastName CHAR(20),
BirthDate DATE
);
Auto Increment ID Fields
You will notice in the create table statements above that the first column is an integer
with some extra arguments used. The first extra argument “auto_increment” tells the
database to automatically assign a unique ID higher than the ID used in previous rows of
this table. This is very useful to do, as you want to be able to refer back to specific rows
of tables when you are writing applications. Next, you see the “primary key” argument,
which works along with auto_increment. Finally, you see the “not null” argument, which
means that an application using this database will throw an error if you try to insert data
into a row in this table and leave the value for this field blank.
Insert Data
Insert is how you input information into the database. To do so, you specify a list of
database column names in parentheses, followed by the words “ values “ followed by a
list of data to insert in single quotes, inside parentheses. Here is the syntax:
Insert into <tbl name> (<column name>, <column name>) values (‘<val1>’, ‘<val2>’);
Ex:
INSERT INTO names (FirstName, LastName, BirthDate) VALUES ('Yamila','Diaz
','1974-10-13');
Inserting multiple rows at once
INSERT INTO names (FirstName, LastName, BirthDate) VALUES
('Nikki','Taylor','1972-03-04'),('Tia','Carrera','1975-09-18');
Exercise: 1
Insert New 10 contact information to names table.
Queering Database
SELECT
[ALL | DISTINCT | DISTINCTROW ]
select_expr, ...
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
Try Following Queries on your database
Selecting all records
SELECT * FROM names;
Selecting base on criteria
SELECT * FROM names WHERE contact_id > 1;
As a condition we can also use NOT NULL. This statement will return all names where
there exists a contact_id.
SELECT * FROM names WHERE contact_id IS NOT NULL;
Result's can be arranged in a particular way using the statement ORDER BY.
SELECT * FROM names WHERE contact_id IS NOT NULL ORDER BY
LastName;
'asc' and 'desc' stand for ascending and descending respectively and can be used to
arrange the results.
SELECT * FROM names WHERE contact_id IS NOT NULL ORDER BY
LastName desc;
You can also place date types into conditional statements.
SELECT * FROM names WHERE BirthDate > '1973-03-06';
LIKE is a statement to match field values using wildcards. The % sign is used for
denoting wildcards and can represent multiple characters.
SELECT FirstName, LastName FROM names WHERE LastName LIKE 'C%';
SQL Logical Operations (operates from Left to Right)
1.NOT or !
2. AND or &&
3. OR or ||
4. = : Equal
5. <> or != : Not Equal
6. <=
7. >=
8 <,>
Here are some more variations with Logical Operators and using the 'IN' statement.
SELECT FirstName FROM names WHERE contact_id < 3 AND LastName LIKE
'D%';
SELECT contact_id FROM names WHERE LastName IN ('Diaz','Carrera');
To return the number of rows in a table
SELECT count(*) FROM names;
SELECT count(FirstName) FROM names;
To do some basic arithmetic aggregate functions.
SELECT SUM(contact_id) FROM names;
select a largest value from a row. Substitute ‘MIN’ and see what happens next.
SELECT MAX(contact_id) FROM names;
BETWEEN
This conditional statement is used to select data where a certain related constraint falls
between a certain range of values. The following example illustrates it's use.
SELECT FirstName, LastName FROM names WHERE contact_id BETWEEN 2 AND
3;
Exercies 2:
Create Following Tables and insert data.
CREATE TABLE address(contact_id SMALLINT NOT NULL PRIMARY KEY,
StreetAddress CHAR(50), City CHAR(20), State CHAR(20), Zip CHAR(15), Country
CHAR(20));
CREATE TABLE telephones (contact_id SMALLINT NOT NULL PRIMARY KEY,
TelephoneHome CHAR(20), TelephoneWork(20));
CREATE TABLE email (contact_id SMALLINT NOT NULL PRIMARY KEY, Email
CHAR(20));
CREATE TABLE company_details (contact_id SMALLINT NOT NULL PRIMARY
KEY, CompanyName CHAR(25), Designation CHAR(15));
INSERT INTO address(contact_id, StreetAddress, City, State, Zip, Country) VALUES
('1', '300 Yamila Ave.', 'Los Angeles', 'CA', '300012', 'USA'),('2','4000 Nikki St.','Boca
Raton','FL','500034','USA'),('3','404 Tia Blvd.','New York','NY','10011','USA');
INSERT INTO company_details (contact_id, CompanyName, Designation) VALUES
('1','Xerox','New Business Manager'), ('2','Cabletron','Customer Support
Eng'),('3','Apple','Sales Manager');
INSERT INTO email (contact_id, Email) VALUES ('1', '[email protected]'),( '2',
'[email protected]'),('3','[email protected]');
INSERT INTO telephones (contact_id, TelephoneHome, TelephoneWork) VALUES
('1','333-50000','333-60000'),('2','444-70000','444-80000'),('3','555-30000','55 5-40000');
Now lets work with multiple tables and see how information can be pulled out of the
data.
SELECT names.contact_id, FirstName, LastName, Email FROM names, email
WHERE names.contact_id = email.contact_id;
SELECT DISTINCT names.contact_id, FirstName, Email, TelephoneWork FROM
names, email, telephones WHERE
names.contact_id=email.contact_id=telephones.contact_id;
JOIN is the action performed on multiple tables that returns a result as a
table. It's what makes a database 'relational'.
There are several types of joins. Let's look at LEFT JOIN (OUTER JOIN) and RIGHT
JOIN
Left Outer Join
SELECT * FROM names LEFT JOIN email USING (contact_id);
To find the people who have a home phone number.
SELECT names.FirstName FROM names LEFT JOIN telephones ON names.contact_id
= telephones.contact_id WHERE TelephoneHome IS NOT NULL;
SELECT FirstName FROM names LEFT JOIN telephones ON names.contact_id =
telephones.contact_id WHERE TelephoneHome IS NOT NULL;
RIGHT JOIN:
SELECT * FROM names RIGHT JOIN email USING(contact_id);
ALTER
The ALTER statement is used to add a new column to an existing table or to make
changes to it.
ALTER TABLE names ADD Age SMALLINT;
SHOW COLUMNS FROM names;
ALTER TABLE names CHANGE COLUMN Age Age TINYINT
ALER TABLE and ADD Constrains
ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name,...)
reference_definition
Exercice:
Add foreign key references for the table for tables.
Rename Table
ALTER TABLE names RENAME AS mynames;
UPDATE
The UPDATE command is used to add a value to a field in a table.
UPDATE names SET Age ='23' WHERE FirstName='Tia';
DELETE
DELETE FROM names WHERE Age=23;
DROP TABLE
DROP TABLE names;
DROP TABLE address ,company_details, telephones;
MySQL Administration with PHPMyAdmin
Lest Try
Create Databases, Create Tables, Insert Data, Query on tables, ALTER tables,
Administration
Create Users, Privileges, Export, Import databases
Exercise 4:
Create Database Call CarRent Using PHP my Admin
Foreign keys
Rent (cust_id) References Customer(Cust_id)
Car (modele_id) Car_Type(modele_id)
Insert data and try some Queries.
Create a user for database and grant access for CarRent Database.
References:
http://www.atlasindia.com/sql.htm
http://dev.mysql.com/doc/refman/5.0/en
MySQL® Phrasebook: Essential Code and Commands