Vous êtes sur la page 1sur 16

PHP Day 08

http://www.php.net
http://www.mysql.com

Geshan Manandhar
Developer,
Young Innovations Private Limited
www.geshanmanandhar.com/slides/php
GeshanManandhar.com 1
MYSQL queries
► MYSQL query with sorting ASC and
DESC
► MYSQL query with limit and offset
► MYSQL query with join 2 tables
► MYSQL query with count, sum, avg,
min
► MYSQL query with string concat
► MYSQL query with like % and _
GeshanManandhar.com 2
tbl_user_test schema

GeshanManandhar.com 3
tbl_test_user instance/data

GeshanManandhar.com 4
Sorting With MYSQL
► SELECT tu.user_id, tu.user_login,
tu.email
FROM tbl_user_test AS tu
ORDER BY tu.user_login ASC;
► SELECT tu.user_id, tu.user_login,
tu.email FROM tbl_user_test as tu
ORDER BY tu.email DESC;
► ASC – Ascending taken by default.

GeshanManandhar.com 5
Limit in MYSQL
► SELECT * FROM `tbl_user_test` LIMIT
1; - select only one row.
► SELECT * FROM `tbl_user_test` LIMIT
1,3; - Select 2nd row and 3 rows
including 2nd row.
 Good to use for pagination

GeshanManandhar.com 6
Table joins with MYSQL
► SELECTtu.user_login, tl.log_text
FROM tbl_user_test AS tu, tbl_log AS tl
WHERE tu.user_id = tl.tbl_user_test_user_id;

GeshanManandhar.com 7
Calculations with MYSQL
► SELECT MIN( tp.price )
FROM tbl_products AS tp; - Applicable
of single column
► SELECT tp.type, MIN( tp.price )
FROM tbl_products AS tp
GROUP BY tp.type; - simple group by.
► SELECT COUNT( * )
FROM tbl_products; - single column
GeshanManandhar.com 8
► SELECTtp.type, COUNT( tp.name )
FROM tbl_products AS tp
GROUP BY tp.type;

GeshanManandhar.com 9
Sum and Average
► SELECT SUM( tp.price )
FROM tbl_products AS tp;
► SELECT tp.type, SUM(tp.price) FROM
tbl_products AS tp GROUP BY tp.type;
► SELECT AVG( tp.price )
FROM tbl_products AS tp;
► SELECT tp.type, AVG(tp.price) FROM
tbl_products AS tp GROUP BY tp.type;
GeshanManandhar.com 10
String Concat
► SELECT CONCAT(tc.first_name, ' ',
tc.middle_name, ' ', tc.last_name) AS
FullName FROM tbl_client AS tc;

GeshanManandhar.com 11
CONCAT_WS
► SELECT CONCAT_WS(' ', tc.first_name,
tc.middle_name, tc.last_name) AS FullName
FROM tbl_client AS tc;

GeshanManandhar.com 12
Select for searches
► SELECT *
FROM `tbl_user_test`
WHERE user_login LIKE 'user%' ;
► %: Matches any number of characters, even
zero characters.

GeshanManandhar.com 13
Select for searches
► SELECT *
FROM `tbl_user_test`
WHERE user_login LIKE 'user_' ;
► _: Matches exactly one character.

GeshanManandhar.com 14
Questions

GeshanManandhar.com 15
Lets run some SQL queries
► Show users in ascending and
descending order as per user_login.
► Show users of row 2-5 in ascending
order as per email.
► Show maximum price from
tbl_products grouped by type.
► Experiment concat and search
queries…
GeshanManandhar.com 16

Vous aimerez peut-être aussi