2013-10-02 27 views
1

我有兩個表,我需要使用where子句。 表1SQL其中空值

CustomerID  Product 
1    Car 
2    Table 
3    Golf 
4    Foo 
5    Yoo 

表2

CustomeID  Comment 
2    Three items 
3    Returned 
4    Complaint 

我有兩個過濾器在where語句這樣

Select * from table1 a left 
join table2 b on a.customerid= b.customerid 
where b.comment<>'Returned' and b.comment not like 'Three%' 

當我運行查詢我剛剛得到一個記錄的查詢。我希望它也返回兩個的customerID的哪些不是在表2(三條記錄)

+0

所以你試圖根據'WHERE'條件過濾掉,但你也想要返回你正在過濾掉的那些?您的預期輸出將以表格形式顯示? –

回答

0

嘗試:

SELECT * 
FROM table1 a 
    LEFT JOIN table2 b on a.customerid= b.customerid 
WHERE (b.comment<>'Returned' and b.comment not like 'Three%') 
     OR (b.customerid is NULL) 
0

我認爲你需要使用LEFT OUTER JOIN:

Select * from table1 a left outer join table2 b on a.customerid = b.customerid where b.comment<>'Returned' and b.comment not like 'Three%' 
0

我通常往往不會加入太多。

SELECT --It's a good practice to enumerate all rows you need, not just *. 
    T1.CUSTOMERID, 
    T1.PRODUCT 
FROM 
    TABLE1 T1 
WHERE 
    T1.CUSTOMERID NOT IN (
     SELECT 
     T2.CUSTOMERID 
     FROM 
     TABLE2 T2 
     WHERE 
     T2.COMMENT !='Returned' AND 
     T2.COMMENT not like 'Three%') 
1
SELECT * FROM Table1 A 
LEFT JOIN Table2 B 
ON A.CustomerID=B.CustomeID  
WHERE (B.COMMENT<>'RETURNED' AND B.COMMENT NOT LIKE 'THREE%') 
OR B.CustomeID IS NULL 

這應該工作,我猜。