尝试加入另一个表时出现Postgres错误,导致错误

时间:2016-10-05 11:23:59

标签: sql postgresql

我的第一张表是:

ID | Code   | Description
1  | IT     | Informatics
2  | GAM    | Gamer
3  | PROG   | Programmer

我的第二张表格如下:

ID | Order  | Catcod
1  | 8080   | {IT,GAM}
2  | 7051   | 
3  | 5601   | PROG

请注意"代码"第一个表中的列是Varchar列,第二个表中的Catcod列是Varchar []列。

我尝试执行的SQL是:

SELECT *
FROM table2 RIGHT OUTER JOIN
     table1 
     ON table2.Catcod = table1.Code

我得到的错误是:

ERROR:  operator does not exist: character varying[] = character varying
LINE 4:  RIGHT OUTER JOIN gc1pbcat on gc1vrkordhdr.catcod = gc1pbcat...
                                                          ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
********** Error **********

ERROR: operator does not exist: character varying[] = character varying
SQL state: 42883
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Character: 216

有没有人知道如何将Varchar []转换为只是Varchar,或者可能拆分数组?

因为我想在表2中的Varchar []中显示Catcode的描述。

更新

或者有人知道我如何将Varchar []转换为Varchar?

1 个答案:

答案 0 :(得分:2)

使用LEFT JOINany()

SELECT *
    FROM table2
    LEFT JOIN table1 on table1.code = any(table2.catcod);

 id | order |  catcod  | id | code | description 
----+-------+----------+----+------+-------------
  1 |  8080 | {IT,GAM} |  1 | IT   | InfOrmatics
  1 |  8080 | {IT,GAM} |  2 | GAM  | GaMer
  2 |  7051 |          |    |      | 
  3 |  5601 | {PROG}   |  3 | PROG | PRogrammer
(4 rows)    

如果您想为订单添加一行,请使用string_agg(),例如:

SELECT table2.id, table2.order, string_agg(description, ', ') description
    FROM table2
    LEFT JOIN table1 on table1.code = any(table2.catcod) 
GROUP BY 1, 2;

 id | order |    description     
----+-------+--------------------
  1 |  8080 | InfOrmatics, GaMer
  2 |  7051 | 
  3 |  5601 | PRogrammer
(3 rows)