postgresql pg_notify函数和row_to_json函数怎么结合使用?

我要使postgresql主动发送通知,将指定数据表的指定一行的数据转换为json字符串,作为通知内容,将通知发给其他的进程,

通过查看官网,我发现有pg_notify和row_to_json这两个函数,pg_notify可以使postgresql主动发送通知给其他进程,row_to_json可以使一行转换为json。

我将这两个写在一起,有以下两个写法,但都抛出了错误

SELECT pg_notify('hello',  (
select  (select row_to_json(t) as json_obj  from (select '1' as a) t) b 
))
SELECT pg_notify('hello',  (
select row_to_json(t.*) as json_obj from (select '1' as a) t
));

错误信息为

SQL 错误 [42883]: ERROR: function pg_notify(unknown, json) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.

如果不用row_to_json,这样写没有问题:

SELECT pg_notify('hello',  (select '1' as a) );

怎么解决该问题,怎么将pg_notify和row_to_json这两个函数写在一起不报错?

阅读 2.1k
2 个回答
✓ 已被采纳

你需要将 json 类型转换为 text 类型:

SELECT pg_notify('hello', (
select row_to_json(t.*)::text as json_obj from (select '1' as a) t
));

参考:
pg_notify
类型转换

postgres里面的函数是强类型的, pg_notify(text, text) 这个是函数定义, 用json返回的类型是json, 匹配不到pg_notify函数, 所以报错. 转换一下类型 ::text 试试.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题