2013-08-24 49 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子句中每個條件測試用於匹配和實體的一組行中的一對值。這使得添加附加條件變得很容易。