为此,您可以使用 JSON 函数或 hstore 扩展名(现在仅对历史感兴趣)使用行的中间键/值表示。 JSON 内置在每个相当新的 PostgreSQL 版本中,而 hstore 必须使用 CREATE EXTENSION 安装在数据库中。
演示:
CREATE TABLE table1 (id int primary key, t1 text, t2 text, t3 text);
让我们插入主键不同的两行和另一列 (t3)。
INSERT INTO table1 VALUES
(1,'foo','bar','baz'),
(2,'foo','bar','biz');
json 解决方案
首先获取具有原始行号的行的键/值表示,然后我们根据原始行号对行进行配对,然后
过滤掉具有相同“值”列的那些
WITH rowcols AS (
select rn, key, value
from (select row_number() over () as rn,
row_to_json(table1.*) as r from table1) AS s
cross join lateral json_each_text(s.r)
)
select r1.key from rowcols r1 join rowcols r2
on (r1.rn=r2.rn-1 and r1.key = r2.key)
where r1.value <> r2.value;
示例结果:
钥匙
-----
ID
t3
hstore 解决方案
SELECT skeys(h1-h2) from
(select hstore(t.*) as h1 from table1 t where id=1) h1
CROSS JOIN
(select hstore(t.*) as h2 from table1 t where id=2) h2;
h1-h2 逐个键计算差异,skeys() 将结果作为集合输出。
结果:
钥匙
--------
ID
t3
可以使用skeys((h1-h2)-'id'::text) 细化选择列表以始终删除id,作为主键,显然行之间总是不同。