问题
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