我有一个查询,我试图简化,使用重复的代码... eek。我是一个SQL初学者(感觉我应该在出现之前把它放在那里!)。
基本上,模式有一个由3个组共享的数据池,我们称之为Parent,Child和GrandChild。父母可以有一个以上的孩子,孩子可以有一个以上的孙子。他们的数据存储在数据表中,并使用其ownerID进行链接。
这种模式不幸地使得向后查找数据变得困难。我想找到标签“Check me”的所有数据,其中dataText是'blahblah'。这要求我找到所有符合此标准的所有OwnerIds,然后从Data表中向后搜索,所有有这个guid的孙子,然后是所有孩子那个guid的GrandChildId等等。一旦我拥有所有ParentIds,我必须钻退缩。
无论如何,特别是我有兴趣删除重复的代码:
Select ParentId, DataFloat, DataText
From [ Demo ] .Data
Where ParentId In
--get the data associated with the parents and union it with the children
((Select Guid
from [ Demo ] .Parent
where Guid In
(Select Guid
From [ Demo ] .Parent
where Guid In
(Select ParentId
From [ Demo ] .Child
Where Guid In
(Select ChildId
From [ Demo ] .GrandChild
where Guid In
(Select ParentId
From [ Demo ] .Data
Left join [ Demo ] .DataColumns as dc
on [ Demo ].Data.DatumColumnId =
dc.DatumColumnId
Left join [ Demo ] .UserLabels as ul
on dc.UserLabelId = ul.UserLabelId
And ul.Label = N'Check me'
And ul.Label is not null
where DataText = N'blahblah')))))
Union All
--get the data associated with the children and union it with the grandchildren
(Select Guid
From [ Demo ] . [ Child ]
Where SampleId In
(Select Guid
From [ Demo ] .Parent
where Guid In
(Select ParentId
From [ Demo ] .Child
Where Guid In
(Select ChildId
From [ Demo ] .GrandChild
where Guid In
(Select OwnerId
From [ Demo ] .Data
Left join [ Demo ] .DataColumns as dc
on [ Demo ].Data.DatumColumnId =
dc.DatumColumnId
Left join [ Demo ] .UserLabels as ul
on dc.UserLabelId = ul.UserLabelId
And ul.Label = N'Check me'
And ul.Label is not null
where DataText = N'blahblah')))))
Union all
--get the data associated with the grandchildren
(Select Guid
From [ Demo ] . [ GrandChild ]
Where ChildId IN
(Select Guid
From [ Demo ] . [ Child ]
Where ParentId IN
(Select Guid
From [ Demo ] .Parent
where Guid In
(Select ParentId
From [ Demo ] .Child
Where Guid In
(Select ChildId
From [ Demo ] .GrandChild
where Guid In
(Select OwnerId
From [ Demo ] .Data
Left join [ Demo ] .DataColumns as dc
on [ Demo ]
.Data.DatumColumnId =
dc.DatumColumnId
Left join [ Demo ] .UserLabels as ul
on dc.UserLabelId =
ul.UserLabelId
And ul.Label = N'blahblah'
And ul.Label is not null
where DataText = N'blahblah')))))))
我尝试过子查询但没有成功。任何使这更容易的提示都会很棒。
由于