tap*_*per 1 postgresql logical-operators
如何在 PostgreSQL 中模拟 XOR 函数?或者,至少,我认为这是一种 XOR 类型的情况。
假设数据如下:
id | col1 | col2 | col3
---+------+------+------
1 | 1 | | 4
2 | | 5 | 4
3 | | 8 |
4 | 12 | 5 | 4
5 | | | 4
6 | 1 | |
7 | | 12 |
Run Code Online (Sandbox Code Playgroud)
我想为那些只填充一列的行返回 1 列。(暂时忽略col3
..
让我们从这个 2 列的例子开始:
SELECT
id, COALESCE(col1, col2) AS col
FROM
my_table
WHERE
COALESCE(col1, col2) IS NOT NULL -- at least 1 is filled in
AND
(col1 IS NULL OR col2 IS NULL) -- at least 1 is empty
;
Run Code Online (Sandbox Code Playgroud)
这很有效,应该导致:
id | col
---+----
1 | 1
3 | 8
6 | 1
7 | 12
Run Code Online (Sandbox Code Playgroud)
但是现在,我想以col3
类似的方式包括在内。像这样:
id | col
---+----
1 | 1
3 | 8
5 | 4
6 | 1
7 | 12
Run Code Online (Sandbox Code Playgroud)
如何做到这一点是一种更通用的方式?Postgres 支持这样的方法吗?
我找不到类似的东西。
仅填充 1 列的行:
select * from my_table where
(col1 is not null)::integer
+(col1 is not null)::integer
+(col1 is not null)::integer
=1
Run Code Online (Sandbox Code Playgroud)
1 或 2 行
select * from my_table where
(col1 is not null)::integer
+(col1 is not null)::integer
+(col1 is not null)::integer
between 1 and 2
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2637 次 |
最近记录: |