MYSQL Query不返回与Join Query无关的内容

时间:2017-07-26 00:48:43

标签: mysql

我写了一个查询来从表“User”中获取所有数据,并从表“Service”中获取相应的“Transaction”计数。我在表1上有100个用户。但目前只有2个用户与服务表有关系。现在我的查询只返回两个结果。但我使用左外部查询来获取与Service表无关的所有用户。

以下是查询:

SELECT users.*, 
count(service.recipient_number) as total_transaction FROM `users`
LEFT OUTER join service ON users.id = service.office_id
WHERE (users.del_status = 0 and service.del_status = 0 and 
users.type="agency") 
group BY users.office_name 

现在输出:

 Username  total_transaction
+++++++++++++++++++++++++++++++++++++
   Dhaka         2
   Ctg           1

欲望输出:

  Username  total_transaction
  +++++++++++++++++++++++++++++++++++++
   Dhaka         2
   Ctg           1
   Sylhet        0
   Comilla       0
   Mym           0

1 个答案:

答案 0 :(得分:0)

SELECT users.office_name,
       count(service.recipient_number) as total_transaction 
FROM `users`
LEFT OUTER JOIN service ON users.id = service.office_id
                        AND service.del_status = 0
                        AND year(curdate()) = year(service.creation_time) 
                        AND month(curdate()) = month(service.creation_time)
WHERE users.del_status = 0  
AND users.type = 'agency'
GROUP BY users.office_name 

您需要将关于联接表的where条件直接放入join

为什么呢?因为where子句会过滤完整的结果集。但join条件仅过滤联接的表结果。