仅使用子表的行计数加入master和child

时间:2013-08-23 11:41:18

标签: sql-server

主表:

CREATE TABLE [dbo].[db_Chat](
    [ChatID] [int] IDENTITY(1,1) NOT NULL,
    [MemberID] [int] NOT NULL,
    [MsgText] [nvarchar](300) COLLATE Chinese_Taiwan_Stroke_CI_AS NOT NULL,
    [DateCreated] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_db_Chat] PRIMARY KEY CLUSTERED 
(
    [ChatID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

子表:

CREATE TABLE [dbo].[db_Chat_Read](
    [ChatReadID] [int] IDENTITY(1,1) NOT NULL,
    [MemberID] [int] NOT NULL,
    [ChatID] [int] NOT NULL,
    [DateCreated] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_db_Chat_Read] PRIMARY KEY CLUSTERED 
(
    [ChatReadID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

我想加入两个表并显示子表的行数,如果没有选择行,那么它可以显示为零。

我知道以下代码可以正常工作。

select c.ChatID, COUNT(*) as ACount  from db_chat c
left join db_Chat_Read r
on c.ChatID = r.ChatID
where c.ChatGroupID=2
GROUP BY c.ChatID

但是我需要在单个SQL代码中使用这样的代码,以下SQL代码无效,但它是为了显示我想要的结果:我需要主表的完整字段,只有子表的行计数。

select c.*, COUNT(r.*)  from db_chat c
left join db_Chat_Read r
on c.ChatID = r.ChatID
where c.ChatGroupID=2

谢谢〜!

1 个答案:

答案 0 :(得分:3)

您可以使用子查询执行所需操作:

select c.*,
       (select COUNT(*) from db_Chat_Read r where c.ChatID = r.ChatId
       ) as ACount
from db_chat c
where c.ChatGroupID = 2;

但是,我建议将列放在group by

编辑:

您还可以使用其他join

执行此操作
select c.*, coalesce(ACount, 0) as ACount
from db_chat c left join
     (select r.ChatId, count(*) as ACount
      from db_Chat_Read r
      group by r.ChatId
     ) r
    on c.ChatID = r.ChatID
where c.ChatGroupID = 2;