假设我的Sql Serer 2008数据库中有3个表:
CREATE TABLE [dbo].[Properties](
[PropertyId] [int] NOT NULL,
[PropertyName] [nvarchar](50) NOT NULL
)
CREATE TABLE [dbo].[Entities](
[EntityId] [int] NOT NULL,
[EntityName] [nvarchar](50) NOT NULL
)
CREATE TABLE [dbo].[PropertyValues](
[EntityId] [int] NOT NULL,
[PropertyId] [int] NOT NULL,
[PropertyValue] [int] NOT NULL
)
Run Code Online (Sandbox Code Playgroud)
我的任务是找到与给定对象完全相同的业务对象(具有完全相同值的完全相同的属性集的对象).表现至关重要.
有什么建议?
[ADDED]例如,Entities表中有一个EntityId = 1的条目.在PropertyValues表中有3行与此条目相关:
EntityId PropertyId PropertyValue
1 4 Val4
1 5 Val5
1 6 Val6
Run Code Online (Sandbox Code Playgroud)
要求是在Entity表中找到PropertyValues表中有3个相关行的其他条目,这些行包含与EntityId = 1的行相同的数据(除了EntityId列)
[已添加]请参阅我的新问题:存储数据的最佳方法,哪些属性可能会有所不同
[BOUNTY1]谢谢大家.答案非常有帮助.我的任务很复杂(但这种复杂性在性能方面很有用).请看下面的详细信息:
现在,有几种类型的实体.每个实体都有自己的一组属性.
是否可以使用此信息提高性能?
[BOUNTY2]有第二个并发症:
问题是:我如何编写一个脚本,为他们选择所有实体和附加列IsValid.
;with cteSource as
(
select PropertyId,
PropertyValue
from PropertyValues
where EntityId = @EntityID
)
select PV.EntityId
from PropertyValues as PV
inner join cteSource as S
on PV.PropertyId = S.PropertyId and
PV.PropertyValue = S.PropertyValue and
PV.EntityId <> @EntityID
group by PV.EntityId
having count(*) = (select count(*)
from cteSource) and
count(*) = (select count(*)
from PropertyValues as PV1
where PV1.EntityId = PV.EntityId)
Run Code Online (Sandbox Code Playgroud)
对于您的添加,您可以添加以下where子句:
where -- exlude entities with deleted properties
PV.EntityID not in (select PV2.EntityID
from Properties as P
inner join PropertyValues as PV2
on P.PropertyID = PV2.PropertyID
where P.IsDeleted = 1)
-- exclude entities with missing EntityType
and PV.EntityID not in (select E.EntityID
from Entities as E
where E.EntityType is null)
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要针对某些示例数据测试查询,可以在此处执行此操作:http: //data.stackexchange.com/stackoverflow/q/110243/matching-properties
| 归档时间: |
|
| 查看次数: |
1031 次 |
| 最近记录: |