简体   繁体   English

使用带有数字的 sql where in 运算符

[英]Using sql where in operator with numbers

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.我知道我可以加入多个 where 语句来实现这一点,但这将是一种更清洁的方法。 Is this possible to do?这是可能的吗?

IN doesn't take operators. IN不接受运算符。 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

You are trying to use "tuples".您正在尝试使用“元组”。

In PostgreSQL tuples can work with equlities or inequalities.在 PostgreSQL 中元组可以处理等式或不等式。 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:只需将组合谓词与OR运算符一起使用,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM