在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中,比较运算符的结果是boolen。
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
如果您尝试将布尔值转换为整数,则会出现错误:
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中将比较运算符的结果作为整数值?
答案 0 :(得分:3)
将布尔值转换为整数:
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)