0

I was trying to fetch distinct users with similar interests and stumbled upon this problem. Basically I wanted to do something like:

SELECT DISTINCT(uid) 
FROM interest 
WHERE (interest , score) IN (('family' , > 0.32), ('paris' , > 0.77));

I get that I can join multiple where statements to achieve this but this would be a more cleaner approach. Is this possible to do?

2 Answers 2

3

IN doesn't take operators. It takes scalar values/tuples or a subquery that returns scalar values/tuples. I think you want:

SELECT DISTINCT uid
FROM interest 
WHERE (interest = 'family' AND score > 0.32) OR
      (interest = 'paris' AND score > 0.77);

You could express this as:

SELECT DISTINCT i.uid
FROM interest i JOIN
     (VALUES ('family', 0.32), ('paris', 0.77)
     ) v(interest, threshold)
     ON i.interest = v.interest and i.score > v.threshold
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for quick answer.
@BrookMG . . . Is there a reason you didn't accept the first answer?
Not really, both of you gave the same answer. I'm grateful. I just picked one.
2

You are trying to use "tuples".

In PostgreSQL tuples can work with equlities or inequalities. In either case ALL values will participate either in the equality or inequality. You cannot mix the operation for different parts of the tuple as you are trying to do: equality for the first element, inequality for the second one. Therefore, in this case you won't be able to use the tuples.

The solution is much simpler. Just use a combined predicate with the OR operator, as in:

SELECT DISTINCT(uid) 
FROM interest 
WHERE interest = 'family' and score > 0.32
   or interest = 'paris' and score > 0.77;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.