2013-08-24 22 views
0

我试图在子查询中使用复合条件,但它没有返回预期的结果。你可以看看下面的例子,看看为什么查询不起作用吗?SQL服务器多个条件子查询

Table : 1 
EntityID StartDate EndDate 

121  2013-08-01 2013-08-31 
122  2013-08-01 2013-08-31 
123  2013-08-01 2013-08-31 


Table : 2 
EntityID  AttributeID AttributeValue 

121   41     304 
122   41     304 
123   41     304 
123   54     307  

现在我想要获取基于属性Id和AttribueValue从表2和Stardate和结束日期从表1使用下面的查询。 (例如:在41和304以及54和307得到了满意的123只我想获取该只123一个记录)

SELECT pe.EntityID 
FROM table1 pe   
WHERE pe.StartDate = '2013-08-01' 
     AND pe.EndDate = '2013-08-31' 
     AND pe.EntityID IN (SELECT peaiv.EntityID 
        FROM table2 peaiv 
        WHERE peaiv.AttributeID IN (41) 
          AND peaiv.[Value] IN (304) 
          AND peaiv.EntityID IN (SELECT peaiv.EntityID 
                FROM 
                  PT_EntityAttributesIntValues 
                  peaiv 
                WHERE peaiv.AttributeID IN (54) 
                  AND peaiv.[Value] IN (307)) 


EntitID 
-------- 
121 
122 
123 

查询返回的上述结果,但我期待的结果只有。任何人都可以试试这个。

+0

是PT_EntityAttributesIntValues table2?并且是peaiv。[Value]应该是peaiv。[AttributeValue]? –

+0

因此,您已经构建了EAV数据库结构,并且发现查询很复杂,并且不会返回您期望的结果?不能说我很惊讶。 – podiluska

回答

2
Declare @Table1 table(EntityID int, StartDate datetime, EndDate datetime) 
Insert into @Table1 
SELECT 121,'2013-08-01','2013-08-31' 
UNION SELECT 122,'2013-08-01','2013-08-31' 
UNION SELECT 123,'2013-08-01','2013-08-31' 

Declare @Table2 Table (EntityID int, AttributeID int , AttributeValue int) 
Insert into @Table2 
SELECT 121,41,304 
UNION SELECT 122,41,304 
UNION SELECT 123,41,304 
UNION SELECT 123,54,307 

SELECT EntityID FROM @Table1 pe 
WHERE 
pe.StartDate = '2013-08-01' AND pe.EndDate = '2013-08-31' 
AND EntityID in 
(SELECT EntityID from @Table2 
WHERE (AttributeID=41 and AttributeValue=304) 
) 
AND EntityID in 
(SELECT EntityID from @Table2 
WHERE (AttributeID=54 and AttributeValue=307) 
) 
2

我将接近这是一个“设置中集”查询,然后再加入回表1来填补这些细节:

select t1.* 
from table1 t1 join 
    (select EntityId 
     from table2 t2 
     group by EntityId 
     having sum(case when AttributeId = 41 and AttributeValue = 304 then 1 else 0 end) > 0 and 
      sum(case when AttributeId = 54 and AttributeValue = 307 then 1 else 0 end) > 0 
    ) t2 
    on t1.EntityId = t2.EntityId; 

having子句中每个条件测试用于匹配和实体的一组行中的一对值。这使得添加附加条件变得很容易。