How to concatenate all results from table row?

喜夏-厌秋 提交于 2020-01-14 18:10:44

问题


Can not find a solution to do something like:

SELECT CONCAT_WS(',', (
    SELECT * FROM table WHERE id = 1
))

How can I do that in PostgreSQL?


回答1:


Quick and dirty:

SELECT t::text FROM tbl t WHERE id = 1;
  • t is an alias for the table and not strictly needed. You can use the original table name as well. But if you have a column of the same name it takes precedence.

  • So t represents the row type of the table, which is automatically coerced to text representation on output.
    I added an explicit cast to make it text internally as well - in case you want to do anything with it ...
    t::text is Postgres short notation for the SQL standard cast (t AS text), which you can use as well. Details in the manual.

  • You may want to trim the (single!) leading and trailing parentheses that denote a row type:

    SELECT right(left(t::text, -1), -1))
    FROM   tbl AS t
    WHERE  id = 1;
    
  • "dirty", becaue you get Postgres row notation, the separator happens to be just the comma you asked for, but some values are also escaped and / or double quoted if needed.



来源:https://stackoverflow.com/questions/23918283/how-to-concatenate-all-results-from-table-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!