sql - 作为 PostgreSQL 中比较运算符的结果返回整数值

标签 sql postgresql

背景

在 MySQL 中,您可以获得比较运算符的结果作为整数值,如下所示。 当您想使用加权匹配分数对 SELECT 的结果进行排序时,此功能很有用。

CREATE TABLE Table1 (`value1` int, `value2` int, `value3` int);

INSERT INTO Table1 (`value1`, `value2`, `value3`)
VALUES             (1, 2, 3),
                   (2, 4, 6),
                   (3, 6, 9);

select value1, value2, value3, 1*(value1=1), 2*(value2=4), 3*(value3=9) from table1;
->  1   2   3   1   0   0
    2   4   6   0   2   0
    3   6   9   0   0   3

问题

在 PostgreSQL 中,比较运算符的结果是 bool 值。

CREATE TABLE Table1 ("value1" int, "value2" int, "value3" int);

INSERT INTO Table1 ("value1", "value2", "value3")
VALUES             (1, 2, 3),
                   (2, 4, 6),
                   (3, 6, 9);

select value1, value2, value3, value1=1, value2=4, value3=9 from table1;
->  1   2   3   true    false   false
    2   4   6   false   true    false
    3   6   9   false   false   true

如果你尝试将 bool 值转换为整数,你会得到一个错误:

select value1, value2, value3, 1*(value1=1), 2*(value2=4), 3*(value3=9) from table1;
ERROR: operator does not exist: integer * boolean Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts. Position: 33

问题

如何在 PostgreSQL 中获取整数值作为比较运算符的结果?

最佳答案

将 bool 值转换为整数:

select value1, value2, value3, 1*(value1=1)::int, 2*(value2=4)::int, 3*(value3=9)::int 
from table1;

 value1 | value2 | value3 | ?column? | ?column? | ?column? 
--------+--------+--------+----------+----------+----------
      1 |      2 |      3 |        1 |        0 |        0
      2 |      4 |      6 |        0 |        2 |        0
      3 |      6 |      9 |        0 |        0 |        3
(3 rows)

关于sql - 作为 PostgreSQL 中比较运算符的结果返回整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080328/

相关文章:

MySQL查询以计算年龄组中的用户数

mysql - 为什么我不断收到 posts.ID 未知列,而该列存在?

postgresql:在事件中拆分时间段

mysql - 了解 postgresql/sql 的细节

sql - 使用 REPLACE INTO 更新表中的时间戳

mySQL JOIN LEFT 不起作用?

sql - 比较 postgres 中的数组

postgresql - 错误 : value seq is not a member of object slick. dbio.DBIO

regex - QGIS "left"或 "strpos"中的表达式生成器不工作

sql - 查询以在特定条件下选择限制