T-SQL在引用表中找到完全相同的值

Ego*_*4eg 2 t-sql sql-server

假设我的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)
  1. 表属性包含可能的属性集,可以为业务对象设置可以设置的值.
  2. 表实体包含从app配置的业务对象.
  3. 表3包含业务对象的选定属性值.每个业务对象都可以包含自己的一组属性(即,可以为第一个对象配置"Property1",但不为第二个对象配置).

我的任务是找到与给定对象完全相同的业务对象(具有完全相同值的完全相同的属性集的对象).表现至关重要.

有什么建议?

[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]谢谢大家.答案非常有帮助.我的任务很复杂(但这种复杂性在性能方面很有用).请看下面的详细信息:

  • 添加了名为EntityTypes的新表
  • EntityTypeId列已添加到"实体"和"属性"表中
  • 现在,有几种类型的实体.每个实体都有自己的一组属性.

    是否可以使用此信息提高性能?

[BOUNTY2]有第二个并发症:

  • IsDeleted列被添加到Property表中
  • PropertyValues表可以具有已从数据库中删除的Properties的值.具有此类属性的实体被视为无效.
  • 某些实体没有EntityType集的每个属性的值.这些实体也被视为无效.

问题是:我如何编写一个脚本,为他们选择所有实体和附加列IsValid.

Mik*_*son 5

;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