简体   繁体   中英

Filter Count Clause - One to Many relationship

I currently have two table where a versionLog can contain many ProductVersions.

Following Sql Query:

SELECT
versionlog.[Name],
(
    SELECT COUNT(*) 
    FROM dbo.ProductVersions productVersion 
    WHERE productVersion.VersionLogId = versionLog.Id  
) AS ProductVersions
FROM dbo.Versionlog versionLog

produces a result set similar to

Name | ProductVersions
Log1  | 12
Log2  |  6
Log3  |  0

etc..

How can I limit the result set to only return Versionlogs with a ProductVersion Count = 0?

According to google I'll need to use the Having clause?

Using HAVING :

SELECT versionlog.[Name]
FROM dbo.Versionlog versionLog
LEFT JOIN dbo.ProductVersions productVersion 
  ON productVersion.VersionLogId = versionLog.Id  
GROUP BY versionlog.[Name]
HAVING COUNT(productVersion.VersionLogId) = 0;

And without grouping:

SELECT versionlog.[Name]
FROM dbo.Versionlog versionLog
LEFT JOIN dbo.ProductVersions productVersion 
  ON productVersion.VersionLogId = versionLog.Id  
WHERE productVersion.VersionLogId IS NULL

another way subquery

select * from 
(
SELECT
versionlog.[Name],
(
    SELECT COUNT(*) 
    FROM dbo.ProductVersions productVersion 
    WHERE productVersion.VersionLogId = versionLog.Id  
) AS ProductVersions
FROM dbo.Versionlog versionLog
) a where a.ProductVersions=0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM