计数和加入

时间:2011-10-20 18:35:05

标签: mysql sql

我有这样的查询:

SELECT c.id, c.name, f.name
FROM companies c
INNER JOIN facilities f ON c.id = f.company
ORDER BY c.name DESC, f.name

我还想为每一行(每个设施)检索COUNT()(一个表)work_orders(一个包含0或1的列)的approved

例如SELECT COUNT(*) FROM work_orders w WHERE w.facility = f.id AND w.approved = 1

结果应该是

company | facility | count
--------------------------
goog    | ohio     | 2
goog    | cali     | 0
tekk    | cupertin | 0

作为一种跟进,我还想添加另一个计数列w.approved = 0

2 个答案:

答案 0 :(得分:2)

SELECT c.id, c.name, f.name, COUNT(w.id) AS work_orders
FROM companies c
INNER JOIN facilities f ON c.id = f.company
-- LEFT JOIN used in case there are facilities with no work orders
LEFT JOIN work_orders w ON f.id = w.facility AND w.approved = 1
GROUP BY c.id, c.name, f.name
ORDER BY c.name DESC, f.name

进行多次计数(已批准或未批准):

SELECT c.id, c.name, f.name, 
  wapp.wo AS approved_work_orders,
  wnapp.wo AS non_approved_work_orders,
FROM companies c
INNER JOIN facilities f ON c.id = f.company
LEFT JOIN (SELECT facility, COUNT(*) AS wo FROM work_orders WHERE approved=1 GROUP BY facility) wapp ON f.id = wapp.facility
LEFT JOIN (SELECT facility, COUNT(*) AS wo FROM work_orders WHERE approved=0 GROUP BY facility) wnapp ON f.id = wnapp.facility
ORDER BY c.name DESC, f.name

答案 1 :(得分:0)

看起来你只需要对c.id和if语句进行分组

SELECT c.id, c.name, f.name, IF(count(0)>0,1,0) 
FROM companies c
INNER JOIN facilities f ON c.id = f.company
LEFT JOIN work_orders w ON w.facility = f.id
GROUP BY f.id
ORDER BY c.name DESC, f.name