2016-02-05 52 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 - 检查更新的答案 –