values lists用于构建常量表,常量表的数据只存在于SQL中,无需在磁盘上创建出来。

values独立使用

例如:

VALUES ('Peter', 'Griffin'), ('Bart', 'Simpson');

postgres=# VALUES ('Peter', 'Griffin'), ('Bart', 'Simpson');

column1 | column2

---------+---------

Peter | Griffin

Bart | Simpson

同时values支持fetch、order by等操作符,使用方法和select类似。

排序:

VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9) ORDER BY column1 DESC;

postgres=# VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9) ORDER BY column1 DESC;

column1 | column2 | column3

---------+---------+---------

7 | 8 | 9

4 | 5 | 6

1 | 2 | 3

fetch:

VALUES

(1, 'Peter', 'Griffin'),

(2, 'Homer', 'Simpson'),

(3, 'Ned', 'Flanders'),

(4, 'Barney', 'Rubble'),

(5, 'George', 'Costanza') FETCH FIRST 3 ROWS ONLY;

postgres=# VALUES

postgres-# (1, 'Peter', 'Griffin'),

postgres-# (2, 'Homer', 'Simpson'),

postgres-# (3, 'Ned', 'Flanders'),

postgres-# (4, 'Barney', 'Rubble'),

postgres-# (5, 'George', 'Costanza')

postgres-# FETCH FIRST 3 ROWS ONLY;

column1 | column2 | column3

---------+---------+----------

1 | Peter | Griffin

2 | Homer | Simpson

3 | Ned | Flanders

values与select结合使用

例如:

postgres=# select * from (values (1, 'a'), (2, 'b'), (3, 'c'));

column1 | column2

---------+---------

1 | a

2 | b

3 | c

postgres=# SELECT * FROM (VALUES (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter);

num | letter

-----+--------

1 | one

2 | two

3 | three

在insert时也比较常用:

drop table t1;

create table t1(

c1 serial primary key,

c2 text default lpad('',500,md5(random()::text))

);

insert into t1 (values(1, 'a'), (2, 'b'), (3, 'c') );

insert into t1 select * from (values(4, 'a'), (5, 'b'), (6, 'c') );

postgres=# select * from t1;

c1 | c2

----+----

1 | a

2 | b

3 | c

4 | a

5 | b

6 | c

需要注意的是,如果常量表需要定义列名给投影部分使用,必须添加column definition list,即AS t (num,letter);,加上CDL之后就可以完全当做一个普通表来使用。

例如:

postgres=# select format(c1, c2) from (values ('hello %s', 'world'), ('hi %s', 'siri'), ('who %s you', 'are')) t(c1, c2);

format

-------------

hello world

hi siri

who are you

(3 rows)

postgres=# select power(a, 2) from generate_series(1, 10) t(a);

power

-------

1

4

9

16

25

36

49

64

81

100

相关阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。