SQL WHERE语句不能与RIGHT JOIN一起使用

时间:2017-03-14 09:35:04

标签: sql

我有以下SQL查询,但问题是WHERE语句无法正常使用RIGHT JOIN:

   SELECT COUNT(*) no_of_application_by_status, applicationStatusName
    FROM `Application` `a`
    right JOIN `ApplicationStatus` `ass` ON `ass`.`applicationStatusId`=`a`.`applicationStatusId`
    WHERE `applicationTypeId` = '40007' 
    GROUP BY `ass`.`applicationStatusId`

Currnet result

我想让applicationStatusName no_of_application_by_status = 0

2 个答案:

答案 0 :(得分:1)

您必须将where条件放入on子句:

SELECT COUNT(*) no_of_application_by_status, applicationStatusName
    FROM `Application` `a`
    right JOIN `ApplicationStatus` `ass` ON `ass`.`applicationStatusId`=`a`.`applicationStatusId`
   and `applicationTypeId` = '40007' 
    GROUP BY `ass`.`applicationStatusId`

如果不这样做,联接结果将被where条件过滤。

答案 1 :(得分:0)

使用Having想要获取群组计数= 0或者如果您只想计算no_of_application_by_status = 0的记录,然后在AND <中使用WHERE条件/ p>

For Group Count = 0

SELECT COUNT(*) no_of_application_by_status, 
    applicationStatusName
FROM Application a
RIGHT JOIN ApplicationStatus ass ON ass.applicationStatusId=a.applicationStatusId
WHERE applicationTypeId = '40007'
HAVING COUNT(*) = 0
GROUP BY ass.applicationStatusId

no_of_application_by_status = 0

的OR计数
SELECT COUNT(*) no_of_application_by_status, 
    applicationStatusName
FROM Application a
RIGHT JOIN ApplicationStatus ass ON ass.applicationStatusId=a.applicationStatusId
WHERE applicationTypeId = '40007' AND no_of_application_by_status = 0
GROUP BY ass.applicationStatusId