2014-05-08 105 views
2

我有一個問題與此SQL查詢:SQL語句的WHERE與從句的故障或操作

SELECT user_id, scrap_id, scrap_text, profile_id, add_date 
FROM scraps 
WHERE profile_id=52 AND user_id=68 OR user_id 
IN(
    SELECT user_id 
    FROM profilecontact 
    WHERE owner_id=68 AND profile_id=52 
); 

與此查詢的問題是這樣的部分,其中OR運算符來在我需要SQL想在下面。方法:

profile_id=52 <- This one should always be followed 
user_id=68 OR user_id IN... <- The result may have user_id 68 OR a user_id that the sub query finds. 

什麼SQL確實是現在它完全忽略這一部分:

profile_id=52 AND user_id=68 

我怎樣才能按照我需要的方式使用OR和AND操作符?

回答

7

你只需要用圓括號組織你的標準。

試試這個:

SELECT user_id, scrap_id, scrap_text, profile_id, add_date 
FROM scraps 
WHERE profile_id=52 AND (user_id=68 OR user_id 
IN(
    SELECT user_id 
    FROM profilecontact 
    WHERE owner_id=68 AND profile_id=52 
)); 

這將把user_ID的標準作爲一個單一的元素和PROFILE_ID作爲另一個AND荷蘭國際集團在一起。