简体   繁体   中英

MySql get count(*) with a join from a table

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:

  1. JOIN creates a cross-product between the two tables, relating them using the ON t2.employeeid = t1.id condition.
  2. Since it's a 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.
  3. It groups these results by the t1.id column, so there will be a single row in the final results for each group.
  4. For each group, it counts all the rows with non-null 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.
  5. Since this count will be NULL if nothing was found, we use IFNULL to convert that to 0 to get a more useful result.
  6. The final results are ordered by the $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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM