MySQL Left Join Count活动并返回null

时间:2017-08-16 13:23:24

标签: mysql

尝试让mysql查询生效。

说明:有两个表,一个包含所有带有org id列的项目,第二个表包含与项目表相关的列projectid的所有活动。我想计算活动表中具有userid并且活动为1的所有活动。 但是这里有棘手的部分,我无法工作。它不会收集活动表中缺少的项目,并将这些项目与计数0一起显示。我想显示所有与bo中唯一项目相对应的项目

SELECT p1.`id` AS projectid ,count(a1.`id`) AS activitiescount ,a1.`userid` AS userid ,p1.`orgid` AS orgid  
FROM `projects` AS p1 
LEFT JOIN `activities` AS a1 
ON p1.`id`=a1.`projectid` 
WHERE p1.`orgid`=3 
AND a1.`userid` = 26 
AND a1.`active`=1 
OR a1.`id` IS null 
GROUP BY p1.`id` 
ORDER BY p1.`name` DESC

给出:

enter image description here

如您所见,例如6和2不正确。 请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

未测试:

将活动限制移至加入。

此外,OR还带回了比你想要的更多,通过移动where子句来解决这个问题也应该得到解决。

标准方法:

SELECT p1.`id` AS projectid 
     , count(a1.`id`) AS activitiescount 
     , a1.`userid` AS userid 
     , p1.`orgid` AS orgid  
FROM `projects` AS p1 
LEFT JOIN `activities` AS a1 
  ON p1.`id`=a1.`projectid` 
 AND a1.`userid` = 26 
 AND a1.`active`=1 
WHERE p1.`orgid`=3 
GROUP BY p1.`id` 
ORDER BY p1.`name` DESC

你的方法w /()正确放置。

SELECT 
    p1.`id` AS projectid 
    ,count(a1.`id`) AS activitiescount 
    ,a1.`userid` AS userid 
    ,p1.`orgid` AS orgid  

FROM `projects` AS p1 
LEFT JOIN `activities` AS a1 ON p1.`id`=a1.`projectid` 

WHERE p1.`orgid`=3 
  AND ((a1.`userid` = 26 AND a1.`active`=1)  OR a1.`id` IS null) 
GROUP BY p1.`id` 
ORDER BY p1.`name` DESC

----更新以模拟每条评论的完整外部联接。

SELECT * 
FROM (
SELECT p1.`id` AS projectid 
     , count(a1.`id`) AS activitiescount 
     , a1.`userid` AS userid 
     , p1.`orgid` AS orgid  
FROM `projects` AS p1 
LEFT JOIN `activities` AS a1 
  ON p1.`id`=a1.`projectid` 
 AND a1.`userid` = 26 
 AND a1.`active`=1 
WHERE p1.`orgid`=3 
GROUP BY p1.`id` 
UNION  
SELECT p1.`id` AS projectid 
     , count(a1.`id`) AS activitiescount 
     , a1.`userid` AS userid 
     , p1.`orgid` AS orgid  
FROM `projects` AS p1 
RIGHT JOIN `activities` AS a1 
  ON p1.`id`=a1.`projectid` 
 AND p1.`orgid`=3 
WHERE a1.`userid` = 26 
 AND a1.`active`=1 
GROUP BY p1.`id`)
ORDER BY p1.`id`,A1.ID -- assumes A1.ID exists and you want to order in that fashion.