Professional Documents
Culture Documents
Comments:
# to end of line, or
-- to end of line, or
/* across multiple lines. */
Table
Primary Key
Normalized
data in a table table, meets certain storage criteria such as a key, and atom field
contents.
Indexes
special columns the developer flags so the data engine may sort and may keep
secondary key lists to optimize performance.
Join
Left Join
The left table in the Join statement is preserved even if there isn't a match with the right
table.
If t1=a,b,c and t2=b,c,d, then LEFT JOIN=a,b,c
Pg - 1 of 43
Table of Contents
PHP COMMUNICATIONS WITH MYSQL...................................................................................................... 4
SELECT & WHERE SYNTAX........................................................................................................................ 5
MYSQL SIMPLE EXAMPLES ....................................................................................................................... 6
STEP 1: CONNECT.................................................................................................................................................... 6
STEP 2: QUERY......................................................................................................................................................... 6
STEP 3: FETCH RESULTS ........................................................................................................................................ 6
STEP 4: EXTRACT INFORMATION FROM FETCH .................................................................................................. 6
SPECIFIC ROW DATA ............................................................................................................................................... 6
ROW COUNT.............................................................................................................................................................. 6
CLOSE CONNECTION............................................................................................................................................... 7
DATA TYPES.............................................................................................................................................. 13
NUMERIC ...................................................................................................................................................................... 13
GEO SPATIAL............................................................................................................................................................... 13
FUNCTIONS ............................................................................................................................................... 14
TEXT.............................................................................................................................................................................. 14
COMMANDS ............................................................................................................................................... 17
AS.................................................................................................................................................................................. 17
CREATE ........................................................................................................................................................................ 17
COUNT .......................................................................................................................................................................... 17
DELETE......................................................................................................................................................................... 17
DISTINCT ...................................................................................................................................................................... 17
INSERT.......................................................................................................................................................................... 17
LIKE............................................................................................................................................................................... 17
ORDER BY .................................................................................................................................................................... 17
PASSWORD.................................................................................................................................................................. 17
SELECT......................................................................................................................................................................... 17
UPDATE ........................................................................................................................................................................ 17
WHERE ......................................................................................................................................................................... 17
ALTER ........................................................................................................................................................................... 17
ADD COLUMN .............................................................................................................................................................. 17
CHANGE COLUMN....................................................................................................................................................... 17
DROPCOLUMN............................................................................................................................................................. 17
ADD INDEX ................................................................................................................................................................... 17
DROP INDEX................................................................................................................................................................. 17
RENAME AS ................................................................................................................................................................. 17
ENGINES .................................................................................................................................................... 17
MyISAM......................................................................................................................................................................... 17
Memory (heap) ............................................................................................................................................................. 17
Merge ............................................................................................................................................................................ 17
InnoDB .......................................................................................................................................................................... 17
Archive.......................................................................................................................................................................... 17
Federated...................................................................................................................................................................... 17
NDBCLUSTER (NDB) ................................................................................................................................................... 17
CSV ............................................................................................................................................................................... 17
Blackhole ...................................................................................................................................................................... 17
Example ........................................................................................................................................................................ 17
Pg - 2 of 43
Pg - 3 of 43
Comments
# comment to end of line
-- comment to end of line
/* This is a multi-line
comment */
Pg - 4 of 43
MySQL WHERE
The WHERE exp is used to MODIFY, DELETE, SELECT, or UPDATE SQL query operations.
= value
equal
!= value
not equal
> value
more than
>= value
more than or equal to
< value
less than
<= value
less than or equal to
BETWEEN value1 AND value2
IN (value1,value2,...)
NOT IN (value1,value2,...)
NOT LIKE value
LIKE stri_ng
the underscore _ matches 1 char
LIKE %string
string ends with, % is 0 or more char
LIKE string%
string starts with, % is 0 or more char
LIKE %string%
string contains, % is 0 or more char
^string
string starts with, ^ represents start of string
Pg - 5 of 43
The following examples assume a db connection has been made using the following code
echo "<h1>Test 1</h1>";
$host = "localhost"; $user = "root"; $pwd = "";
$db = mysqli_connect($host, $user, $pwd);
mysqli_select_db($db, "test");
STEP 2: QUERY
Next, you must query the database for a result set. The result set is unusable until a fetch is used (next
step)
$query = "SELECT * FROM t1 WHERE fname = Mickey"; // single row (1d array)
$result = mysqli_query($db, $query) or die(mysqli_error($db));
or multiple rows would be like this
$query = "SELECT * FROM t1";
// multiple rows (2d array)
$result = mysqli_query($db, $query) or die(mysqli_error($db));
STEP 3: FETCH RESULTS
=
=
=
=
mysqli_fetch_row($result))
mysqli_fetch_array($result))
mysqli_fetch_assoc($result))
mysqli_fetch_object($result))
//
//
//
//
There are two ways to extract the information. If the information was fetched as an index than array numbers
will be used to access field values. If the information was fetched as an assoc, than field names may be used.
echo First name is . $row[2];
// indexed row: Mickey
echo First name is . $rows[2];
// indexed array: Mickey or current row name
echo First name is . $rows[fname]; // assoc array: Mickey or current row name
SPECIFIC ROW DATA
When an assoc or indexed array is being accessed, each row of information is incremented by each FETCH call. A chosen row of
information may be accessed by using
$result =
$row_cnt =
or
$result =
$row_cnt =
or
$result =
$row_cnt =
or
$result =
$row_count
Pg - 6 of 43
or
$result
CLOSE CONNECTION
mysql_close($db);
Pg - 7 of 43
/*
+-------------------------------------------------------------------+
|
|
|
File:
php_mysql_test.php
Version:
2012-02-04
|
|
|
|
Purpose:
shows syntax for most common mysql operations
|
|
using improved mysql"i"
|
|
|
+-------------------------------------------------------------------+
//
<----------
maintenance support
*/
---------->
$debug = 'false';
if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php')) {
include($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php');
}
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 'on');
//
<----------
start html
---------->
if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css')) {
echo '<html><head>';
include($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css');
echo '</head><body>';
}else{
echo '<html>
<head>
<style>
body {
font-family: courier;
/* background-color: #500; /* dark red */
background-color: #002;
/* midnight blue */
color: #ddd;
margin-left:
100;
margin-right: 100;
margin-top:
50;
margin-bottom: 50;
}
</style>
</head>
<body>';
}
//
<----------
db connect
---------->
//
<----------
delete db
---------->
//
<----------
create db
---------->
//
<----------
connect to db
---------->
//
<----------
delete table
---------->
//
<----------
create table
---------->
Pg - 8 of 43
//
<----------
add record
---------->
//
<----------
---------->
//
<----------
update record
---------->
//
<----------
delete record
---------->
//
<----------
---------->
//
<----------
--------->
$database = "test_db";
$result = mysqli_select_db($db,$database) or die(mysqli_error());
$loop = mysqli_query($db, "SHOW TABLES FROM $database") or die('SHOW TABLES: cannot select tables');
Pg - 9 of 43
<td>"
<td>"
<td>"
<td>"
</tr>";
.
.
.
.
$col[2]
$col[3]
$col[4]
$col[5]
.
.
.
.
"</td>
"</td>
"</td>
"</td>
$i++;
} //end row loop
echo "</table><br/>";
} //end table loop
echo "<br/>";
//
<----------
--------->
//
<----------
--------->
//
<----------
--------->
mysqli_close($db);
echo 'Mysql connection closed, end of program.';
echo "
</BODY>
</HTML>";
?>
Pg - 10 of 43
Output
There are 2 records with names starting with 'M'.
Array
(
[id] => 1
[name] => Mickey Mouse
[age] => 50
[updated] => 2012-02-06 22:09:52
[update_by] => janz
[note] => na
)
1Array
(
[id] => 2
[name] => Mini Mouse
[age] => 36
[updated] => 2012-02-06 22:09:52
[update_by] => janz
[note] => na
)
1
people
table structure
Field
Type :
Length
Key Index
Default
id
int(11)
NO
name
varchar(25)
YES
age
int(3)
YES
updated
timestamp
NO
CURRENT_TIMESTAMP
NO
unknown
update_by varchar(25)
note
PRI
varchar(255) YES
Extra
auto_increment
on update
CURRENT_TIMESTAMP
na
id,int(11),NO,PRI,,auto_increment
name,varchar(25),YES,,,
age,int(3),YES,,,
updated,timestamp,NO,,CURRENT_TIMESTAMP,on update CURRENT_TIMESTAMP
update_by,varchar(25),NO,,unknown,
note,varchar(255),YES,,na,
Array
(
[Table] => people
[Create Table] => CREATE TABLE `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) DEFAULT NULL COMMENT 'first name',
`age` int(3) DEFAULT NULL COMMENT 'yrs',
`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
COMMENT 'last update',
`update_by` varchar(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name',
`note` varchar(255) DEFAULT 'na',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
)
1
Mysql connection closed, end of program.
Pg - 11 of 43
Pg - 12 of 43
DATA TYPES
NUMERIC
CHAR
LONG VARCHAR
BIT
FLOAT
INT
SMALLINT
DATE
DATETIME
More...
Up to 2 GB of characters.
Holds a value of 0 or 1 (Boolean). It is primarily used for yes/no and true/false issues.
This type holds decimal numbers. It is primarily used for mathematical purposes.
This stores whole numbers between -2,147,483,648 and 2,147,483,648.
As above except you are limited to numbers between -32,768 and 32,768.
This will store a date.
This will store a date and time (timestamp). It is primarily used to Time Stamp entries or updates to a row or
table.
There are at least 5 date, 15 text, 8 numeric, 20 accounting data types.
GEO SPATIAL
GEOMETRY
GEOMETRYCOLLECTION
LINESTRING
MULTILINESTRING
MULTIPOINT
MULTIPOLYGON
POINT
POLYGON
OPERATOR
=
<>
<
<=
>
>=
IS NULL
NOT NULL
OR
AND
%
_
[ ]
Comparison
Compares the data to your criteria to see if it is equal
Compares the data to your criteria to see if it is not equal
Compares the data to your criteria to see if the data is less than your criteria
Compares the data to your criteria to see if the data is less than or equal to your criteria
Compares the data to your criteria to see if the data is greater than your criteria
Compares the data to your criteria to see if the data is greater than or equal to your criteria
Checks the data to make sure that there is no data in the column
Requires a value in the column, often used for key fields.
Connects multiple condition tests
Connects multiple condition tests
Wildcard, match all characters before
Wildcard
Wildcard
OPERATOR
ASC
DESC
Sorting
Sort by scending order A to Z
Sort by descending order Z to A
Pg - 13 of 43
FUNCTIONS
NUMERIC
ABS()
ACOS()
ASIN()
ATAN()
SYNTAX
EXAMPLE
SELECT ABS(-2);
return: 2
Returns the arccosine of numeric expression. Returns SELECT ACOS(1);
return: 0.000000
NULL if the value is not in the range -1 to 1.
SELECT ASIN(1);
Returns the arcsine of numeric expression. Returns
return: 1.5707963267949
NULL if value is not in the range -1 to 1
SELECT ATAN(1);
Returns the arctangent of numeric expression.
return: 0.78539816339745
Returns the absolute value of numeric expression.
ATAN2()
BIT_AND()
BIT_COUNT()
BIT_OR()
CEIL()
CEILING()
Returns the smallest integer value that is not less than SELECT CEILING(3.46);
passed numeric expression
return: 4
CONV(N,from_base,
to_base)
COS()
COT()
SELECT
MAKER, BIT_AND(PRICE) BITS
FROM CARS GROUP BY MAKER
return:
MAKER
BITS
-------------CHRYSLER
512
FORD
12488
HONDA
2144
SELECT
BIT_COUNT(2) AS TWO,
BIT_COUNT(4) AS FOUR,
BIT_COUNT(7) AS SEVEN
return:
| TWO | FOUR | SEVEN |
|
1 |
1 |
3 |
SELECT
MAKER, BIT_OR(PRICE) BITS
FROM CARS GROUP BY MAKER
return:
MAKER
BITS
-------------CHRYSLER 62293
FORD
16127
HONDA
32766
SELECT CONV(5,16,2);
return: 101
DEGREES()
EXP()
Returns the base of the natural logarithm (e) raised to SELECT EXP(3);
the power of passed numeric expression.
return: 20.085537
FLOOR()
FORMAT()
GREATEST()
SELECT GREATEST(33,99,34,55,67);
return: 99
INTERVAL()
SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);
return: 6
SELECT LEAST(3,5,1,8,33,99,34,55,67,43);
return: 1
LOG()
SELECT LOG(45);
return: 3.806662
LOG(B,X)
SELECT LOG(2,65536);
LEAST()
Pg - 14 of 43
SELECT FLOOR(7.55);
return: 7
return: 16.000000
LOG10()
MOD()
OCT()
PI()
POW()
POWER()
SELECT POWER(3,3);
return: 27
RADIANS()
SELECT RADIANS(90);
return: 1.570796
ROUND()
SELECT ROUND(5.693893);
return: 6
SELECT SIGN(-4.65);
return: -1
SIN()
SELECT SIN(90);
return: 0.893997
SQRT()
SELECT SQRT(49);
return: 7
STD()
STDDEV()
TAN()
TRUNCATE()
ROUND()
SIGN()
ROUND(5.693893,2)
return: 5.69
SELECT TRUNCATE(7.536432,2);
return: 7.53
TEXT
GROUP
(Aggregate)
MAX( )
MIN( )
SUM( )
AVG( )
COUNT( )
CONCAT
CONCAT(col1,col2)
SYSTEM INFO
SHOW DATABASES;
SHOW ENGINES;
SHOW DATABASES;
Pg - 15 of 43
PRIVILEGES
User Privileges
ALTER
ALTER ROUTINE
CREATE
CREATE ROUTINE
Create routine
DROP
EXECUTE
INDEX
INSERT
LOCK TABLES
REPLICATION CLIENT
REPLICATION SLAVE
SELECT
SHOW DATABASE
SHOW VIEW
UPDATE
Admin Privileges
CREATE USER
DROP USER
FILE
GRANT OPTION
PROCESS
RELOAD
REVOKE
SHUTDOWN
SUPER
OPERATOR
ADMIN PRIVILEGES
EXAMPLE
GRANT
PASSWORD
(your password)
PASSWORD
(user password)
Pg - 16 of 43
COMMANDS
Command
AS
(aliase)
CREATE
COUNT
Syntax
Example
SELECT company_col,
COUNT(*) AS co_sales_total_col
FROM sales_tbl
GROUP BY company_col
ORDER BY company_col ASC;
DELETE
DISTINCT
(No duplicates)
INSERT
new info or
copy table
LIKE
(case insensitive
or wildcards)
SELECT MAX(amount_col)
FROM receipts_tbl
WHERE date_col = '01/01/2002'
SELECT AVG(sales_col)
FROM receipts_table
WHERE date_col = '01/01/2002';
SELECT COUNT(msg_col) AS count_col
FROM msg_tbl
WHERE category = 'SQL';
SELECT COUNT(DISTINCT job_type_col)
FROM jobs_tbl;
DELETE FROM <table>
WHERE <condition>;
SELECT DISTINCT <col>
FROM <table>;
INSERT INTO <table> (<col>, <col>, <col>)
VALUES (value, value, 'value');
INSERT INTO <table> (<col>, <col>, <col>)
SELECT col1, col2, col3 FROM other_tbl;
INSERT INTO <table> (<col>, <col>, <col>)
VALUES (value, value, 'value');
SELECT <col>, <col> # or SELECT *
FROM <table>
WHERE <condition>
<col> LIKE <condition>
SELECT *
FROM <table>
ORDER BY <col>; ascending is default
ASC = ascending
or
DESC = descend
ORDER BY <col> <direction>;
ORDER BY
PASSWORD
(your password)
PASSWORD
(user password)
SELECT
UPDATE
CONCAT(lname,,,fnamecol2)
AS fullname FROM contacts;
CREATE TABLE contacts (
contact_id INT IDENTITY (1, 1) NOT NULL,
first_name CHAR (30) NULL ,
last_name CHAR (50) NULL ,
email
VARCHAR (75) NULL
);
SELECT COUNT(*) AS sales_total
FROM sales;
company_name
---------------Amazon.com
Sears
CompUSA
Dollar General Stores
company_sales
------------------------478
222
512
6
company_name
---------------Amazon.com
CompUSA
Dollar General Stores
Sears
company_sales
------------------------478
512
6
222
Pg - 17 of 43
WHERE
(case sensitive)
ALTER
ADD COLUMN
CHANGE
COLUMN
DROPCOLUMN
ADD INDEX
SYNTAX
EXAMPLE
DROP INDEX
RENAME AS
ENGINES
Name
MyISAM
Memory
(heap)
Merge
InnoDB
Archive
Federated
NDBCLUSTER
(NDB)
CSV
Blackhole
Example
DESCRIPTION
The default MySQL storage engine and the one that is used the most in Web, data warehousing, and other
application environments. MyISAM is supported in all MySQL configurations, and is the default storage engine
unless you have configured MySQL to use a different one by default.
Stores all data in RAM for extremely fast access in environments that require quick lookups of reference and other
like data.
Allows a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as
one object. Good for VLDB environments such as data warehousing.
Used for transaction processing applications, and sports a number of features including ACID transaction support
and foreign keys.
Provides the perfect solution for storing and retrieving large amounts of seldom-referenced historical, archived, or
security audit information.
Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very
good for distributed or data mart environments.
This clustered database engine is particularly suited for applications that require the highest possible degree of
uptime and availability.
The CSV storage engine stores data in text files using comma-separated values format. You can use the CSV
engine to easily exchange data between other software and applications that can import and export in CSV
format.
The Blackhole storage engine accepts but does not store data. Retrievals always return an empty set. The
functionality can be used in distributed database design where data is automatically replicated, but not stored
locally.
Tables can be created, but no data can be stored or retrieved. This engine serves as an example in MySQL
source code. It illustrates how to begin writing new storage engines but does nothing.
Pg - 18 of 43
USER OPERATIONS
Update database permissions / privileges.
flush privileges;
Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
# mysql -u root -p
use mysql;
INSERT INTO user (Host,User,Password)
VALUES('%','username',PASSWORD('password'));
flush privileges;
Change a users password FROM unix shell.
mysql/path/mysqladmin -u username -h hostname.blah.org -p password 'newpassword'
Change a users password FROM MySQL prompt. Login as root. Set the password. Update privs.
# mysql -u root -p
SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
flush privileges;
Recover a MySQL root password.
Stop the MySQL server process.
Start again with no grant TABLEs.
Login to MySQL as root.
Set new password.
Exit MySQL and restart MySQL server.
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-TABLEs &
# mysql -u root
use mysql;
update user set password=PASSWORD("newrootpassword") WHERE User='root';
flush privileges;
quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is no root password.
# mysqladmin -u root password newpassword
Update a root password.
# mysqladmin -u root -p oldpassword newpassword
Allow the user "bob" to connect to the server FROM localhost using the password "passwd".
Login as root. Switch to the MySQL db. Give privileges. Update privileges.
# mysql -u root -p
use mysql;
grant usage on *.* to bob@localhost identified by 'passwd';
flush privileges;
Give user privileges for a db.
Login as root.
Switch to the MySQL db.
Pg - 19 of 43
Pg - 20 of 43
DATABASE OPERATIONS
Create a database.
mysql_query("CREATE DATABASE dbName",$db);
To delete a db.
mysql_query("DROP DATABASE dbName",$db);
List all databases on the sql server.
mysql_query("SHOW DATABASES",$db);;
Switch to or select a database.
USE dbName;
BACKUP all databases. Backup file is sql commands to recreate all db's.
mysql/path/mysqldump -u username p password --opt > /path/all_db.sql
or
mysql/path/mysqldump -u username p password all-databases > /path/all_db.sql
BACKUP one database.
mysql/path/mysqldump -u username p password --databases dbName >
/path/dbName.sql
Restore database (or database TABLE) FROM backup.
mysql/path/mysql -u username p password databasename < /tmp/databasename.sql
Batch or script.
mysql/path/mysql -u username p password < /path/script.txt
# use -t for nice TABLE layout and -vvv for command echoing.
mysql/path/mysql > /path/script.txt
Load CSV COMMA DELIMITED file into a TABLE.
LOAD DATA LOCAL INFILE '/path/filename.csv'
replace INTO TABLE t1
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' (field1,field2,field3);
Load TAB DELIMITED file into a TABLE.
LOAD DATA LOCAL INFILE '/path/filename.tab' into table dbNAME.t1 fields
terminated by 't' enclosed by '"' lines terminated by 'rn';
# rn mean new lines. r means carriage return. n means new line.
Pg - 21 of 43
TABLE OPERATIONS
Show all TABLES in current db.
SHOW TABLES;
Show database column format.
DESCRIBE t1;
DELETE a TABLE.
DROP TABLE t1;
TRUNCATE a TABLE. (deletes TABLE, then recreate with same fields, the reset the AUTO INCREMENT counter to '0')
DROP TABLE t1;
Clear and reset a table. Deletes, re-creates, set auto-inc to 0
truncate table t1;
SHOW all data in a TABLE.
SELECT * FROM t1;
UPDATE an existing row in TABLE.
UPDATE t1 SET c1 = 'something' WHERE c2 = 'somewhere';
Delete a row(s) FROM a TABLE.
DELETE FROM t1 WHERE c1 = 'whatever';
Rename TABLE.
ALTER TABLE IF EXISTS `my_orig_table` RENAME `my_new_name`;
Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.
SHOW COLUMNS FROM t1;
Dump a TABLE FROM a database.
mysql/path/mysqldump -c -u username -ppassword databasename TABLEname >
/tmp/databasename.TABLEname.sql
Copy table structure
CREATE TABLE t1 SELECT * FROM t2
Create TABLE Example 1.
CREATE TABLE t1 (
id INT PRIMARY KEY,
c1 VARCHAR(35),
datestamp DATE,
timestamp time
); # end of table
Create TABLE Example 2.
create TABLE t1 (
id int(50) NOT NULL AUTO_INCREMENT PRIMARY KEY,
c1 varchar(35),
c2 varchar(50) DEFAULT 'hello')
; # end of table
Pg - 22 of 43
COLUMN OPERATIONS
Delete a COLUMN.
ALTER TABLE t1 DROP COLUMN c1;
Add a new COLUMN to TABLE.
ALTER TABLE t1 ADD COLUMN newName varchar(20);
Rename COLUMN name.
ALTER TABLE t1 change oldName newName varchar(50);
Make a UNIQUE COLUMN so you get no dupes.
ALTER TABLE t1 ADD UNIQUE c1;
Make a COLUMN bigger.
ALTER TABLE t1 MODIFY c1 VARCHAR(3);
Delete UNIQUE FROM TABLE.
ALTER TABLE t1 DROP INDEX c1;
Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.
SHOW COLUMNS FROM t1;
Selecting column.
SELECT c1 FROM t1;
SELECT c1, c2 FROM t1 WHERE c2 = "smith" ORDER BY c2;
Sorting.
SELECT c1, c2 FROM t1 ORDER BY c2;
SELECT c1, c2 FROM t1 ORDER BY c2 DESC; # reverse
Pg - 23 of 43
Where conditions
The WHERE exp is used to modify a DELETE, SELECT, or UPDATE SQL query.
Syntax
t1, t2 are TABLE names
c1, c2 are COLUMN or FIELD names
$result is a resource OBJECT
$rows is an array of records
$row is a single RECORD
$db is a database object
Simple statement
Pg - 24 of 43
SELECT * FROM t1
Advanced statement using WHERE
SELECT <*|c1,c2,...> ALIASE <label1,lable2,...>
FROM <t1,t2,...>
WHERE exp AND|OR exp AND|OR exp...
ORDER BY <c1,c2,...>
This list shows the format you can use when writing a WHERE exp (expression). The where exp can be one
of the following:
column
column
column
column
column
column
column
column
column
column
column
column
column
column
column
= value
equal
!= value
not equal
> value
more than
>= value
more than or equal to
< value
less than
<= value
less than or equal to
BETWEEN value1 AND value2
IN (value1,value2,...)
NOT IN (value1,value2,...)
NOT LIKE value
LIKE stri_ng
the underscore _ matches 1 char
LIKE %string
string ends with, % is 0 or more char
LIKE string%
string starts with, % is 0 or more char
LIKE %string%
string contains, % is 0 or more char
^string
string starts with, ^ represents start of string
Pg - 25 of 43
Distinct counts.
SELECT c1, COUNT(*) FROM t1 GROUP BY c1; # distinct count
or
SELECT count(distinct c1) as distinct_items FROM t1);
Sum COLUMN.
SELECT SUM(c1) FROM t1;
MAXIMUM value.
SELECT MAX(c1) AS label FROM t1;
Pg - 26 of 43
Character
Meaning
Example
Match
Not a Match
Beginning of line
^c
cat
my cat
End of line
c$
tic
stick
..
me, go
mea?n
mean, men
moan
()
m(ea)n
mean
men,mn
[]
abc[1-3]
abc1,abc2
abc4
[! ]
m[!ea]n
min, mon
men, man
One or more
door[1-3]+
Zero or more
door[1-3]*
door, door311
door4, door445
{,}
Range of repetitions
a{2,5}
aa,aaaaa
a, xx3
Escapes character
m\*n
m*n
men, mean
(||)
Alternate strings
Pg - 27 of 43
Thomas, To
Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN:
Return all rows from the right table, even if there are no matches in the left table. A
right join is identical to a left join if the position of the tables is swapped.
FULL JOIN:
Merges the tables (including unmatched rows) as if a LEFT and RIGHT JOIN where
used at the same time.
UNION:
Adds returned rows of one table to the returned rows of another table.
GROUP:
Adds returned rows of one table to the returned rows of another table.
Test db setup:
To demonstrate joins consider a database named test with two tables with a
customer ID in common, when with credit limits, and the other with phone numbers.
The each have customer id rows that are unique and two rows that are in common.
We delibertly have different column names for the ID to show that the key field does
not have to be named the same.
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Pg - 28 of 43
JOIN(default), INNER JOIN, and WHERE: Return rows when there is a match in both tables. Note, that a
WHERE is often used as a shortcut to this type of JOIN. An
INNER JOIN is the same as a JOIN.
SELECT *
FROM t1, t2
WHERE t1.cust_id = t2.cust_num
or
SELECT *
FROM t1
JOIN t2
WHERE t1.cust_id = t2.cust_num
or
SELECT *
FROM t1
INNER JOIN t2 ON t1.cust_id = t2.cust_num
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Result:
cust_id
credit
cust_num
phone
100.00
123-4567
150.00
234-5678
Pg - 29 of 43
LEFT JOIN: Return all rows from the left table, even when no match is found in the right table.
The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility and
doesn't add any extra capabilities.
SELECT *
FROM t1
LEFT JOIN t2 ON t1.cust_id = t2.cust_num
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Result:
cust_id
credit
cust_num
phone
50.00
NULL
NULL
75.00
NULL
NULL
100.00
123-4567
150.00
234-5678
Pg - 30 of 43
RIGHT JOIN: Return all rows from the right table, even when no match is found in the left table. Note that a
RIGHT JOIN can be duplicated by swapping table positions and using a LEFT JOIN.
The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility and
doesn't add any extra capabilities.
SELECT *
FROM t1
RIGHT JOIN t2 ON t1.cust_id = t2.cust_num
or
SELECT *
FROM t2
LEFT JOIN t1 ON t1.cust_id = t2.cust_num
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Result:
cust_id
credit
cust_num
phone
100.00
123-4567
150.00
234-5678
NULL
NULL
345-6789
NULL
NULL
456-7890
Pg - 31 of 43
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Result:
cust_id
credit
cust_num
phone
50.00
NULL
NULL
75.00
NULL
NULL
100.00
123-4567
150.00
234-5678
NULL
NULL
345-6789
NULL
NULL
456-7890
Pg - 32 of 43
UNION: returns a table with column positions merged to the first tables field names.
SELECT * FROM t1
UNION
SELECT * FROM t2
Table t1
cust_id
credit
1
50
2
75
3
100
4
150
Table t2
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890
Result:
cust_id
credit
50.00
75.00
100.00
150.00
123-4567
234-5678
345-6789
456-7890
Pg - 33 of 43
Pg - 34 of 43
MONTH(NOW()) AS m;
DAYOFMONTH(NOW()) AS d;
HOUR(NOW()) AS h;
MINUTE(NOW()) AS m;
SECOND(NOW()) AS s;
// 731676, use
Pg - 35 of 43
PERIOD_ADD() - adds an interval (in months) to a date and returns a new date
Date Datatypes
There are 5 MySQL date datatypes these are:
Datatype
Format
Info
DATETIME
YYYY-MM-DD HH:MM:SS
DATE
YYYY-MM-DD
TIMESTAMP(length)
Varies
See Below
TIME
HH:MM:SS
YEAR
YYYY
The timestamp datatype is somewhat different as it stores the time that a row was last changed. The format
also varies according to the length. For example to store the same information as DATETIME, you would specify
a length of 14 whereas to store the DATE you would specify a length of 8.
Timestamp Definition
Format
TIMESTAMP(2)
YY
TIMESTAMP(4)
YYYY
TIMESTAMP(6)
YYMMDD
TIMESTAMP(8)
YYYYMMDD
TIMESTAMP(10)
YYMMDDHHMM
TIMESTAMP(12)
YYMMDDHHMMSS
TIMESTAMP(14)
YYYYMMDDHHMMSS
In the 'cds' table we have used the DATE for the 'bought' field.
mysql> SELECT cds.title, cds.bought
-> FROM cds;
+------------------------------+------------+
| title
| bought
|
+------------------------------+------------+
| A Funk Odyssey
| 2001-10-10 |
| Now 49
| 2001-10-15 |
| Eurovision Song contest 2001 | 2000-09-08 |
| Abbas Greatest Hits
| 2000-11-05 |
| Space Cowboy
| 2001-10-10 |
| Sign of the times
| 1987-11-07 |
| The White Album
| 1994-07-20 |
| The Hits
| 1993-10-07 |
| westlife
| 2000-06-09 |
+------------------------------+------------+
So to begin with let's look at how we can manipulate these dates using MySQL's date functions.
DATE_FORMAT()
This function allows the developer to format the date anyway that they wish by specifying a sequence of format
strings. A string is composed of the percentage symbol '%' followed by a letter that signifies how you wish to
display part of the date. These are some of the more common strings to use:
Pg - 36 of 43
String
Displays
Example
%d
01....10....17....24 etc
%D
%m
01....04....08....11 etc
%M
January....April....August etc
%b
Jan....Apr....Aug....Nov etc
%y
%Y
%W
Weekday name
%a
Mon....Wed....Fri etc
%H
07....11....16....23 etc
%h
07....11....04....11 etc
%p
AM or PM
AM....PM
%i
Minutes
01....16....36....49 etc
%s
Seconds
01....16....36....49 etc
There are more, but that should be enough for now. There are a couple of things to note. Upper and Lowercase
letters in the string make a difference and also that when arranging these strings into a sequence you can
intersperse 'normal' characters. For example:
The sequence '%d/%m/%y', with forward slashes separating the strings, would be displayed as 01/06/03.
The next stage is to use the function DATE_FORMAT() to convert a stored time to a format we want.
Syntax:
DATE_FORMAT(date, sequence)
Thus to change the format of the cds.bought field to DD-MM-YYYY we specify the field as the date and the
sequence as '%d-%m-%Y'.
DATE_FORMAT(cds.bought, '%d-%m-%Y')
This function is then incorporated into our SQL statement in place of the exiting cds.bought field.
Pg - 37 of 43
Extraction Functions
As well as using DATE_FORMAT() there are other functions that allow you to extract specific information about a
date (year, month, day etc). These include:
Function
Displays
Example
DAYOFMONTH(date)
01....10....17....24 etc
DAYNAME(date)
MONTH(date)
01....04....08....11 etc
MONTHNAME(date)
January....April....August etc
YEAR(date)
HOUR(time)
07....11....16....23 etc
MINUTE(time)
Minutes
01....16....36....49 etc
SECOND(time)
Seconds
01....16....36....49 etc
DAYOFYEAR(date)
1.....366
To give an example of one of these you can use DAYNAME() to work out which day you were born on. To do this
you can specify the date directly to the function without referring to any tables or field. So for my birthday (20th
July 1973):
+-----------------------+
| DAYNAME('1973-07-20') |
+-----------------------+
| Friday
|
+-----------------------+
1 row in set (0.00 sec)
Or you could even SELECT two or three date items.
mysql> SELECT DAYNAME('1973-07-20'), MONTHNAME('1973-07-20'), YEAR('1973-07-20');
+-----------------------+-------------------------+--------------------+
| DAYNAME('1973-07-20') | MONTHNAME('1973-07-20') | YEAR('1973-07-20') |
+-----------------------+-------------------------+--------------------+
| Friday
| July
|
1973 |
+-----------------------+-------------------------+--------------------+
1 row in set (0.02 sec)
Pg - 38 of 43
+---------------------+-----------+------------+
| NOW()
| CURTIME() | CURDATE() |
+---------------------+-----------+------------+
| 2003-06-02 19:44:51 | 19:44:51 | 2003-06-02 |
+---------------------+-----------+------------+
1 row in set (0.01 sec)
We can also format this result as well using DATE_FORMAT() and using an alias to
tidy up the title:
mysql> SELECT
-> DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), '%W the %D of %M %Y')
-> AS 'Six Months Ago';
+---------------------------------+
| Six Months Ago
|
+---------------------------------+
| Monday the 2nd of December 2002 |
+---------------------------------+
1 row in set (0.01 sec)
Pg - 39 of 43
Pg - 40 of 43
do {
code block...
}
while (condition);
MYSQL FUNCTIONS
mysql_affected_rows ..............
mysql_client_encoding ............
mysql_close ..........................
mysql_connect ......................
mysql_create_db ...................
mysql_data_seek ...................
mysql_db_name ....................
mysql_db_query ....................
mysql_drop_db .....................
mysql_errno .........................
mysql_error ..........................
mysql_escape_string ..............
mysql_fetch_array .................
mysql_fetch_assoc .................
mysql_fetch_field ..................
mysql_fetch_lengths ..............
mysql_fetch_object ................
mysql_fetch_row ...................
mysql_field_flags ...................
mysql_field_len .....................
mysql_field_name ..................
mysql_field_seek ...................
mysql_field_table ...................
mysql_field_type ...................
mysql_free_result ..................
mysql_get_client_info .............
mysql_get_host_info ..............
mysql_get_proto_info .............
mysql_get_server_info ...........
mysql_info ............................
mysql_insert_id .....................
mysql_list_dbs ......................
mysql_list_fields ....................
mysql_list_processes ..............
mysql_list_tables ...................
mysql_num_fields ..................
mysql_num_rows ...................
mysql_pconnect ....................
mysql_ping ...........................
mysql_query .........................
mysql_real_escape_string .......
mysql_result .........................
mysql_select_db ....................
mysql_set_charset .................
mysql_stat ...........................
mysql_tablename ..................
mysql_thread_id ....................
mysql_unbuffered_query .........
Pg - 41 of 43
Pg - 42 of 43
Notes: _______________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
Pg - 43 of 43