0

这里参考

我做了以下查询:

SELECT INSTITUTE.ID INST_ID,
  INSTITUTE.PLACEMENT PLACEMENT,
  INSTITUTE.ADDRESS INSTITUTE_LOCATION,
  COUNT(DISTINCT INSTITUTE_DEPARTMENT.id) departments
--  COUNT(DISTINCT INSTITUTE_CAMPUS.id) campuses
FROM INSTITUTE
LEFT JOIN INSTITUTE_DEPARTMENT
ON (INSTITUTE.id = INSTITUTE_DEPARTMENT.institute_id)
LEFT JOIN INSTITUTE_COURSE
ON (INSTITUTE.ID = INSTITUTE_COURSE.INSTITUTE_ID)
LEFT JOIN INSTITUTE_CAMPUS
ON (INSTITUTE.ID                       = INSTITUTE_CAMPUS.INSTITUTE_ID)
WHERE INSTITUTE.ID                     = 1761
AND INSTITUTE.IS_ACTIVE                = 1
AND INSTITUTE.IS_DELETED               = 0
AND INSTITUTE.DELETED_DATE            IS NULL
--AND INSTITUTE_CAMPUS.IS_ACTIVE         = 1
--AND INSTITUTE_CAMPUS.IS_DELETED        = 0
--AND INSTITUTE_CAMPUS.DELETED_DATE     IS NULL
AND INSTITUTE_DEPARTMENT.IS_ACTIVE     = 1
AND INSTITUTE_DEPARTMENT.IS_DELETED    = 0
AND INSTITUTE_DEPARTMENT.DELETED_DATE IS NULL
GROUP BY INSTITUTE.ID, INSTITUTE.PLACEMENT, INSTITUTE.ADDRESS

我正在正确计算部门字段。

INST_ID | PLACEMENT | INSTITUTE_LOCATION | DEPARTMENTS
 1761     NIIT           Noida              2 

但是通过包括校园计数(这个 insitute_id 上的校园计数为 0),我得到了空行。

In short, when count are o null rows are returned while rows are returned when count are greater than 0.
4

1 回答 1

2

您应该将您的校园条件置于 LEFT JOIN 条件而不是 where 条件。如果你把它放在过滤你的 compaus 表的地方。试试这个

SELECT INSTITUTE.ID INST_ID,
INSTITUTE.PLACEMENT PLACEMENT,
INSTITUTE.ADDRESS INSTITUTE_LOCATION,
COUNT(DISTINCT INSTITUTE_DEPARTMENT.id) departments
COUNT(DISTINCT INSTITUTE_CAMPUS.id) campuses
FROM INSTITUTE
LEFT JOIN INSTITUTE_DEPARTMENT
ON (INSTITUTE.id = INSTITUTE_DEPARTMENT.institute_id)
LEFT JOIN INSTITUTE_COURSE
ON (INSTITUTE.ID = INSTITUTE_COURSE.INSTITUTE_ID)
LEFT JOIN INSTITUTE_CAMPUS
ON (INSTITUTE.ID                       = INSTITUTE_CAMPUS.INSTITUTE_ID AND INSTITUTE_CAMPUS.IS_ACTIVE = 1 AND INSTITUTE_CAMPUS.IS_DELETED = 0 AND INSTITUTE_CAMPUS.DELETED_DATE IS NULL)
WHERE INSTITUTE.ID                     = 1761
AND INSTITUTE.IS_ACTIVE                = 1
AND INSTITUTE.IS_DELETED               = 0
AND INSTITUTE.DELETED_DATE            IS NULL
AND INSTITUTE_DEPARTMENT.IS_ACTIVE     = 1
AND INSTITUTE_DEPARTMENT.IS_DELETED    = 0
AND INSTITUTE_DEPARTMENT.DELETED_DATE IS NULL
GROUP BY INSTITUTE.ID, INSTITUTE.PLACEMENT, INSTITUTE.ADDRESS

这行得通!

于 2012-06-02T09:49:23.080 回答