问题
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 ittext
internally as well - in case you want to do anything with it ...t::text
is Postgres short notation for the SQL standardcast (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