如果我的计数行为0,则查询无结果

时间:2018-08-28 13:24:54

标签: mysql sql

我有一个用户数据库。我想返回信息,包括它们所在的组数。我执行以下SQL查询

"Spain"

这将不返回任何结果,因为在任何组中都不存在用户ID 27,当它显示其他信息并且组/队行应为0时。

这对于一个组或多个组中的用户很好用

3 个答案:

答案 0 :(得分:1)

也许是因为您使用的是隐式INNER JOIN ...请使用显式的LEFT JOIN。

尝试一下:

SELECT dbo.Users.UserId AS 'userId', 
       dbo.Users.UserName AS 'firstName', 
       dbo.Users.Surname AS 'surname', 
       dbo.Users.Photograph AS 'photograph', 
       dbo.Users.JobTitle AS 'jobTitle', 
       dbo.Users.EmailAddress AS 'emailAddress', 
       dbo.Users.Inactive AS 'inactive', 
       COALESCE(COUNT(dbo.UserGroups.userId), 0) AS 'teams'
 FROM dbo.Users left join
       dbo.UserGroups on dbo.UserGroups.UserId = dbo.Users.UserId
 WHERE dbo.Users.UserId = 27  
 GROUP BY dbo.Users.UserId, 
       dbo.Users.UserName, 
       dbo.Users.Surname, 
       dbo.Users.Photograph, 
       dbo.Users.JobTitle, 
       dbo.Users.EmailAddress, 
       dbo.Users.Inactive

答案 1 :(得分:0)

您应该使用left join而不是隐式inner join

SELECT dbo.Users.UserId AS 'userId', 
       dbo.Users.UserName AS 'firstName', 
       dbo.Users.Surname AS 'surname', 
       dbo.Users.Photograph AS 'photograph', 
       dbo.Users.JobTitle AS 'jobTitle', 
       dbo.Users.EmailAddress AS 'emailAddress', 
       dbo.Users.Inactive AS 'inactive', 
       COUNT(dbo.UserGroups.userId) AS 'teams'
 FROM dbo.Users
 LEFT JOIN dbo.UserGroups ON dbo.UserGroups.UserId = dbo.Users.UserId
 WHERE dbo.Users.UserId = 27 
 GROUP BY dbo.Users.UserId, 
       dbo.Users.UserName, 
       dbo.Users.Surname, 
       dbo.Users.Photograph, 
       dbo.Users.JobTitle, 
       dbo.Users.EmailAddress, 
       dbo.Users.Inactive

答案 2 :(得分:0)

我将建议一个相关的子查询:

SELECT u.*,
       (SELECT COUNT(*) FROM dbo.UserGroups ug WHERE ug.UserId = u.UserId) as teams
FROM dbo.Users u 
WHERE u.UserId = 27 ;

为什么我更喜欢这种方法?

  • 它使查询更简单。您不必列出GROUP BY中的所有列。
  • 因为没有外部GROUP BY,所以这可能是大多数数据库上性能最高的(假设UserGroups(UserId)上有索引)。
  • 请注意使用表别名来简化查询。