How to select columns that have name beginning with same prefix?

余生长醉 提交于 2021-02-11 15:30:05

问题


Using PostgreSQL 8.1.11, is there a way to select a set of columns that have name beginning with same prefix.

Suppose we have columns : PREFIX_col1, PREFIX_col2, ...

Is it possible to do a request like :

SELECT 'PREFIX_*' FROM mytable;

Which of course doesn't work.


回答1:


information_schema.COLUMNS contains all the columns in your db so you can query for a specific pattern in the name like this:

select column_name from information_schema.COLUMNS as c where c.TABLE_NAME = 'mytable' and c.COLUMN_NAME like 'PREFIX_%';



回答2:


You are going to have to construct the query with a query and use EXECUTE. Its a little easier w/ 8.3+. Here's a query that will run on 8.1 and pulls all columns starting with r% from the film table

$$
DECLARE 
   qry  TEXT;
BEGIN
    SELECT 'SELECT ' || substr(cols, 2, length(cols) - 2) ||
      ' FROM film' INTO qry
    FROM (
        SELECT array(
            SELECT quote_ident(column_name::text)
            FROM information_schema.columns 
            WHERE table_schema = 'public'
              AND table_name = 'film'
              AND column_name LIKE 'r%'
            ORDER BY ordinal_position
        )::text cols 
        -- CAST text so we can just strip off {}s and have column list
    ) sub;

    EXECUTE qry;
END;
$$



回答3:


To me it looks like the syntax description of PostgreSQL 8.x's SELECT statement does not allow this. A SELECT list must be an expression or list of expressions, and the syntax for expressions does not seem to allow for wildcarded partial column names.

Share and enjoy.



来源:https://stackoverflow.com/questions/3941156/how-to-select-columns-that-have-name-beginning-with-same-prefix

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