0

主表:

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

谢谢~!

4

1 回答 1

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;
于 2013-08-23T12:01:41.423 回答