2016-02-05 51 views
1

所以我想從表A中獲取一些數據,如果某些屬性可用於這些項目。我使用下列標準篩選出的記錄爲mssql加入混淆

select * from product p 
inner join AttributeCodesByProduct atp 
on atp.product_id = p.product_id 
AND LTRIM(RTRIM(atp.attrVal)) LIKE 'Sil - ghi' 
OR LTRIM(RTRIM(atp.attrVal)) LIKE 'Sil - def' 
OR LTRIM(RTRIM(atp.attrVal)) LIKE 'Sil - abc' 
OR LTRIM(RTRIM(atp.attrVal)) not like 'xyz' 

where p.class = 2 

基本上我想檢索與2級的所有產品,並檢查屬性表,以確保他們有屬性,如(「實 - GHI」,「 Sil - def','Sil - abc')並且沒有像'xyz'這樣的屬性。我不確定它是否應該是正確的連接或內部連接,但我不希望任何額外的屬性項。對於單個產品,可能有許多不同的屬性。

感謝任何幫助。

回答

0

更好的方式來寫你的查詢

SELECT * 
FROM product p 
     INNER JOIN attributecodesbyproduct atp 
       ON atp.product_id = p.product_id 
        AND Ltrim(Rtrim(atp.attrval)) IN ('Sil - ghi','Sil - def', 'Sil - abc') 
WHERE p.class = 2 

,或者如果你不想包括product當它有一個ATLEAST作爲'xyz'屬性那就試試這個

SELECT * 
FROM product p 
     INNER JOIN attributecodesbyproduct atp 
       ON atp.product_id = p.product_id 
WHERE p.class = 2 
     AND Ltrim(Rtrim(atp.attrval)) IN ('Sil - ghi', 'Sil - def', 'Sil - abc') 
     AND EXISTS (SELECT 1 
        FROM product p1 
          INNER JOIN attributecodesbyproduct atp1 
            ON atp1.product_id = p1.product_id 
        WHERE p.product_id = p1.product_id 
        GROUP BY p1.product_id 
        HAVING Count(CASE WHEN Ltrim(Rtrim(atp.attrval)) = 'xyz' THEN 1 END) = 0) 
+0

理解,但我有這個還有其他子句「LTRIM(RTRIM(atp.attrVal))不像'xyz'」。並且在這種情況下內連接是正確的連接類型? – Eclipse

+0

@Eclipse - 檢查更新的答案 –