主表:
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
谢谢~!