如果至少有一个子项使用两个表,如何选择父行

时间:2012-05-10 15:48:49

标签: sql sql-server

你好我有数据表和2个小问题的表格。

CREATE TABLE [dbo].[Parent] (
    [id] [int] NOT NULL,
    [Name] [nvarchar](50) NOT NULL, 
 CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[Child1] (
    [Child1Id] [int] NOT NULL,
    [ParentId] [int] NOT NULL,
    [SomeData] [int] NOT NULL,  
 CONSTRAINT [PK_Child1] PRIMARY KEY CLUSTERED 
(
    [Child1Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[Child2] (
    [Child2Id] [int] NOT NULL,
    [ParentId] [int] NOT NULL,
    [SomeData] [int] NOT NULL,  
 CONSTRAINT [PK_Child2] PRIMARY KEY CLUSTERED 
(
    [Child2Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


INSERT INTO Parent VALUES(1,'Name 1')
INSERT INTO Parent VALUES(2,'Name 2')
INSERT INTO Parent VALUES(3,'Name 3')
INSERT INTO Parent VALUES(4,'Name 4')


INSERT INTO [Child1] VALUES(1,1,50)
INSERT INTO [Child1] VALUES(2,1,125)
INSERT INTO [Child1] VALUES(3,2,255)


INSERT INTO [Child2] VALUES(1,1,2)
INSERT INTO [Child2] VALUES(2,2,4)
INSERT INTO [Child2] VALUES(3,2,8)
INSERT INTO [Child2] VALUES(4,3,16)
  1. 如何在两个表中选择所有包含至少一个子类型的parets记录。 我做了下一个查询 但我不知道显示此记录总数的最佳方式

    SELECT p.Name,count(Child1),count(Child2)

  2. 如何选择仅存在于两个表中的所有parets记录? SELECT p.Name,count(Child1),count(Child2)

  3. 感谢建议。

1 个答案:

答案 0 :(得分:2)

查询1:

--at least one child record in either Child1 or Child2
select distinct p.*
from parent p
left outer join child1 c1 on p.id = c1.ParentId
left outer join child2 c2 on p.id = c2.ParentId
where coalesce(c1.ParentId, c2.ParentId) is not null

查询2:

--at least one child record in both Child1 and Child2
select distinct p.*
from parent p
inner join child1 c1 on p.id = c1.ParentId
inner join child2 c2 on p.id = c2.ParentId

注意:如果您只想显示父记录的数量,请更改

select distinct p.*

select count(distinct p.id)

在任一查询中。