duanmiyang6201 2018-10-06 11:01
浏览 548
已采纳

pq:函数unnest(未知)不是唯一的

Following code is working fine. But I want to define array['a', 'b', 'c', 'd', 'e'] as a variable.

rows, err :=  db.Query("select colname from (SELECT date, unnest(array['a', 'b', 'c', 'd', 'e']) AS colname, unnest(array[a, b, c, d, e]) AS thing from test1 where date='123') as tester where thing=1;")

So I try following code using github.com/lib/pq .

arr1 := []string{"a", "b", "c", "d", "e"}      
rows, err :=  db.Query("select colname from (SELECT date, unnest($1) AS colname, unnest($1) AS thing from test1 where date='123') as tester where thing=1;", pq.Array(arr1))

But getting error like "pq: function unnest(unknown) is not unique". Table structure and sample data--

test=# \d+ test1
                                Table "public.test1"
 Column |         Type          | Modifiers | Storage  | Stats target | Description 
--------+-----------------------+-----------+----------+--------------+-------------
 a      | character varying(10) |           | extended |              | 
 b      | character varying(10) |           | extended |              | 
 c      | character varying(10) |           | extended |              | 
 d      | character varying(10) |           | extended |              | 
 e      | character varying(10) |           | extended |              | 
 date   | character varying(10) |           | extended |              | 

test=# select * from test1 ;
 a | b | c | d | e | date 
---+---+---+---+---+------
 3 | 1 | 3 | 2 | 3 | 124
 3 | 3 | 2 | 2 | 1 | 125
 1 | 2 | 2 | 1 | 3 | 126
 1 | 2 | 3 | 2 | 3 | 127
 1 | 1 | 2 | 2 | 3 | 123
(5 rows)

Basically I want the column name (a,b,c,d or e) which have value '1' on any specific date.

  • 写回答

1条回答 默认 最新

  • dougang1605 2018-10-06 19:54
    关注

    I'd guess that pq.Array is giving you a PostgreSQL array in the string form so you end up with something like this:

    unnest('{a,b,c,d,e}')
    

    and PostgreSQL isn't sure how it should interpret that string, hence the complaint about unnest(unknown). You should be able to add an explicit type cast to clear things up:

    unnest($1::text[])         -- PostgreSQL-specific casting syntax
    unnest(cast($1 as text[])) -- Standard casting syntax
    

    You'd end up with something like this:

    rows, err :=  db.Query("select colname from (SELECT date, unnest($1::text[]) AS colname, unnest($1) AS thing from test1 where date='123') as tester where thing=1;", pq.Array(arr1))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘