2012-02-29 246 views
4
ArticleNumber Company Storage 
01-01227  12  2 
01-01227  2  1 'filtered by company/storage in combination 
01-01227  5  1 
01-01227  12  1 'filtered by company/storage in combination 
01-44444  5  4 'filtered by not match the articlenumber 

欲進行過濾,從而含有行(company = 12storage = 1)和(company = 2storage = 1)將被過濾掉的結果集,並過濾上articlenrSQL查詢到兩個字段篩選組合

這就是我想到的,但肯定有一個更簡單的方法來做出該查詢?

SELECT * FROM MyTable 
where 
    (Company=2 and Storage<>1 and ArticleNumber='01-01227') 
or 
    (Company=12 and Storage<>1 and ArticleNumber='01-01227') 
or 
    (Company<>2 and Company<>12 and ArticleNumber='01-01227') 

結果後我:

ArticleNumber Company Storage 
    01-01227  12  2 
    01-01227  5  1 
+0

你說你想'過濾掉'company = 5和storage = 1,並且你正在返回查詢... – 2012-02-29 14:33:25

+0

對不起,應該是公司2和存儲1!我現在改變了它。 – Stefan 2012-02-29 14:39:56

+0

我剛剛提供了兩個答案 – 2012-02-29 14:40:33

回答

0

這將返回你要查找的內容:

select * from t 
where articleNumber = '01-01227' and (
    (company != 12 or storage != 1) and 
    (company != 2 or storage != 1) 
) 

結果:

ARTICLENUMBER COMPANY STORAGE 
01-01227  12  2 
01-01227  5  1 

沒有必要在此解決方案的加入,這使它相當快速和高性能。除此之外,您可以輕鬆地添加restrinctions成對。

+0

太棒了!它的工作原理並不是一團糟。 ;) – Stefan 2012-02-29 14:48:50

+0

謝謝:)見到你! – 2012-02-29 14:50:39

0

一個可能的方法來簡化這一過程是建立一個稱爲表,說company_storage_excludeCompanyStorage列。然後,只需與要排除對CompanyStorage填充這些值,然後你可以這樣做:

select * 
from MyTable 
where (Company,Storage) not in (select Company,Storage from company_storage_exclude) 
and ArticleNumber='01-01227'; 

或:

select a.* 
from MyTable a 
left join company_storage_exclude b 
on (a.Company=b.Company and a.Storage=b.Storage) 
where b.Company is null and b.Storage is null 
and ArticleNumber='01-01227'; 
0
SELECT * FROM MyTable 
WHERE 
    NOT (Company=12 and Storage=1) 
AND 
    NOT (Company=5 and Storage=1) 
AND 
    ArticleNumber='01-01227' 

甚至更​​好

SELECT * FROM MyTable 
WHERE 
    NOT ((Company=12 OR Company=5) AND Storage=1) 
AND 
    ArticleNumber='01-01227' 
+1

錯過了OP的文章編號限制 – 2012-02-29 14:25:51

+0

哎呀錯過了 - 修正了 – trapper 2012-02-29 14:42:21

0

沿着這些線?

SELECT * FROM MyTable 
where 
    ArticleNumber='01-01227' 
AND 
    (Company IN (2,12) AND Storage <> 1 
    OR 
    Company NOT IN (2,12) 
    ) 
+0

這個查詢不會過濾出與文章編號01-44444由於某種原因的行。 – Stefan 2012-02-29 14:37:06

1
SELECT * FROM MyTable 
WHERE ArticleNumber='01-01227' 
AND (Company NOT IN (2,12) OR Storage <> 1)