erol_smsr
erol_smsr

Reputation: 1496

SQL statement WHERE clause trouble with OR operator

I have an issue with this SQL query:

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
);

The problem with this query is this part where the OR operator comes in. I need SQL to think in the following way:

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.

What SQL does now is it completely ignores this part:

profile_id=52 AND user_id=68

How can I use the OR and AND operators the way I need them?

Upvotes: 2

Views: 77

Answers (1)

crthompson
crthompson

Reputation: 15865

You just need to organize your criteria with parenthesis.

Try this:

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
));

This will treat the the user_id criteria as a single element and the profile_id as another, ANDing them together.

Upvotes: 7

Related Questions