六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 169|回复: 0

postgresql-从子查询中构造数组

[复制链接]

升级  94.2%

305

主题

305

主题

305

主题

进士

Rank: 4

积分
971
 楼主| 发表于 2013-1-30 01:35:02 | 显示全部楼层 |阅读模式
声明:本PostgreSQl实用指南系列为刘兴(http://deepfuture.iteye.com/)原创,未经笔者授权,任何人和机构不能转载
子查询的结果中构造一个数组
D:\pgsql>psql mydb
psql (8.4.2)
Type "help" for help.
mydb=#
mydb=# select * from student,citys where student.city=citys.id
mydb-# ;
    name    | age | city |  sex  | name | id
------------+-----+------+-------+------+----
 艾丝凡     |  18 |    3 |       | 上海 |  3
 萨芬       |  19 |    3 |       | 上海 |  3
 未来       |  20 |    2 | man   | 湛江 |  2
 干哈       |  18 |    2 | man   | 湛江 |  2
 deepfuture |  20 |    1 | woman | 长沙 |  1
 张三       |  21 |    1 | woman | 长沙 |  1
 王五       |  25 |    3 | man   | 上海 |  3
 李白       |  23 |    2 | man   | 湛江 |  2
 李国       |  24 |    1 | woman | 长沙 |  1
(9 rows)
 

mydb=# select citys.name as 城市,array(select name from student where student.ci
ty=citys.id) as 学生 from citys;
 城市 |          学生
------+------------------------
 长沙 | {deepfuture,张三,李国}
 湛江 | {未来,干哈,李白}
 上海 | {艾丝凡,萨芬,王五}
(3 rows)

mydb=# select * from student;
    name    | age | city |  sex
------------+-----+------+-------
 艾丝凡     |  18 |    3 |
 萨芬       |  19 |    3 |
 未来       |  20 |    2 | man
 干哈       |  18 |    2 | man
 deepfuture |  20 |    1 | woman
 张三       |  21 |    1 | woman
 王五       |  25 |    3 | man
 李白       |  23 |    2 | man
 李国       |  24 |    1 | woman
(9 rows)

mydb=# select * from citys;
 name | id
------+----
 长沙 |  1
 湛江 |  2
 上海 |  3
(3 rows)

mydb=#
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表