Mostly not able to think through what to do,
I have two database tables. Say table_employee and table_workorder
every employee have one/many workorder.
Earlier i was using to queries, one to get employee tuple from table_employee and other query for every employee workorder count.
SELECT * from table_employee order by " . $orderBy ." desc"
SELECT count(*) as wcount from table_workorder where employeeid = " . $table_employee.id;
I realized instead of 2 DB calls, it would be nice to have a single call that can fetch me results, but i am unable to frame the query. Trying in MySql coupled with PHP
SELECT t1.*, IFNULL(COUNT(t2.employeeid), 0) AS wcount
FROM table_employee AS t1
LEFT JOIN table_workorder AS t2 ON t2.employeeid = t1.id
GROUP BY t1.id
ORDER BY $orderBy DESC
You need to use a LEFT JOIN
so that you'll get rows for employees with no work orders.
Here's how this works:
ON t2.employeeid = t1.id
condition. LEFT JOIN
, any rows in the first table with no matching row in the second table will be put in the result set, with NULL
for all the columns in the second table. t1.id
column, so there will be a single row in the final results for each group. t2.employeeid
. As mentioned in step 2, the employees with no matching work orders will get NULL
for t2.employeeid
, so they won't be counted. NULL
if nothing was found, we use IFNULL
to convert that to 0
to get a more useful result. $orderBy
column. This is exactly what your sequence of queries does, but it's all done in one SQL query.
Here's a good tutorial on SQL JOINs:
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.