Page is a not externally linkable
- Code, Content, and Presentation
-- Databases
---- Join statment WITH Where and Order By clauses


rocknbil - 4:20 pm on Jun 19, 2012 (gmt 0)


I always get this wrong off the top of my head and have to mantra, it goes in this order:

select/from/join/where/order/limit

I'm guessing at a few of the field names.

$sql =
"select tbl_admin_users.username, tbl_access_log.login,tbl_access_log.logout
from tbl_admin_users
left join tbl_access_log on tbl_access_log.fld_user_id = tbl_admin_users.fld_user_id
where tbl_access_log.fld_user_id = '" . $adminId . "'
order by tbl_access_log.fld_logout desc limit 1";

Some notes:

- Do not use * unless you specifically need all fields, it's a lot of overhead that will cost you on complex multi table joins.
- If admin ID is numeric, which it should be, it doesn't need to be quoted (and shouldn't.)

where tbl_access_log.fld_user_id = $adminId
If it's just a single table select, and you're sure it always will be (i.e., no other potential joins in the near future) you can move the "joining" to the where clause:

$sql =
"select tbl_admin_users.username, tbl_access_log.login, tbl_access_log.logout
from tbl_admin_users,tbl_access_log
where tbl_access_log.fld_user_id = $adminId
and tbl_access_log.fld_user_id = tbl_admin_users.fld_user_id
order by tbl_access_log.fld_logout desc limit 1";


Thread source:: http://www.webmasterworld.com/databases_sql_mysql/4449196.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com