2012-05-10 35 views
0

您好,我有一個帶有數據和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,計數(Child1),計數(CHILD2)

  2. 如何選擇只有所有parets記錄在兩個表中都存在? SELECT p.Name,count(Child1),count(Child2)

Thanks in Advice。

回答

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) 

在任一查詢中。

+0

嗨RedFilter,我需要在每個子表中callulate記錄計數。我需要得到reuslt像:名稱,計數(fromChild1),計數(fromChild2) –

+0

@cleric請提供所需的輸出示例。例如 – RedFilter

+0

結果應該是這樣的:Name 1 | 2(在child1中計數)| 1(在child2中計數),名稱2 | 1(在child1中計數)| 3(在child2中計數)等 –

相關問題