开发者

PostgreSQL: dynamically create result columns

I want to "dynamically" create the result columns in a PostgreSQL query. I have these tables:

CREATE SEQUENCE 开发者_开发问答users_id;
CREATE TABLE users (
  id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('users_id'),
  name VARCHAR(128) NOT NULL
);

CREATE SEQUENCE quota_rules_id;
CREATE TABLE quota_rules (
  id INT PRIMARY KEY NOT NULL DEFAULT NEXTVAL('quota_rules_id'),
  user_id INT REFERENCES users(id),
  rule VARCHAR(255) NOT NULL
);
CREATE INDEX user_id_index ON quota_rules(user_id);

INSERT INTO users (name) VALUES ('myname'); -- id=1
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'a');
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'b');
INSERT INTO quota_rules (user_id, rule) VALUES (1, 'c');

And want a query that returns this (1 row):

SELECT ............ user_id = 1;
name   | quota_rule | quota_rule2 | quota_rule3
myname | a          | b           | c


Check out the crosstab function of the tablefunc module

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜