Postgresql function returns composite - how do I access composite values as separate columns?

霸气de小男生 提交于 2019-12-12 11:54:26

问题


I have a Postgresql function which returns a composite type defined as (location TEXT, id INT). When I run "SELECT myfunc()", My output is a single column of type text, formatted as:

("locationdata", myid)

This is pretty awful. Is there a way to select my composite so that I get 2 columns back - a TEXT column, and an INT column?


回答1:


Use:

SELECT * 
  FROM myfunc()

You can read more about the functionality in this article.




回答2:


Answer has already been accepted, but I thought I'd throw this in:

It may help to think about the type of the data and where those types fit into an overall query. SQL queries can return essentially three types:

  • A single scalar value
  • A list of values
  • A table of values

(Of course, a list is just a one-column table, and a scalar is just a one-value list.)

When you look at the types, you see that an SQL SELECT query has the following template:

SELECT scalar(s)
FROM table
WHERE boolean-scalar

If your function or subquery is returning a table, it belongs in the FROM clause. If it returns a list, it could go in the FROM clause or it could be used with the IN operator as part of the WHERE clause. If it returns a scalar, it can go in the SELECT clause, the FROM clause, or in a boolean predicate in the WHERE clause.

That's an incomplete view of SELECT queries, but I've found it helps to figure out where my subqueries should go.



来源:https://stackoverflow.com/questions/3799551/postgresql-function-returns-composite-how-do-i-access-composite-values-as-sepa

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