关于SELECT

最近更新时间: 2024-10-17 17:10:00

select用于从一张表或视图中获取数据。

使用select …from…命令查询数据

示例说明:

示例:

1)分组查询,排序

查询销售明细表,按dep,product汇总,排序展示

create table t_grouping(id int,dep varchar(20),product varchar(20),num int);
insert into t_grouping values(1,'业务1部','手机',90);
insert into t_grouping values(2,'业务1部','电脑',80);
insert into t_grouping values(3,'业务1部','手机',70);
insert into t_grouping values(4,'业务2部','电脑',60);
insert into t_grouping values(5,'业务2部','手机',50);
insert into t_grouping values(6,'业务2部','电脑',60);
insert into t_grouping values(7,'业务3部','手机',70);
insert into t_grouping values(8,'业务3部','电脑',80);
insert into t_grouping values(9,'业务3部','手机',90);
select dep,product,sum(num) from t_grouping group by dep,product order by dep,product;

2)(左连接)表连接(类型内连接、左连接、右连接、全连接)

select * from tbase left join t_appoint_col on tbase.id=t_appoint_col.id;

3)子查询,排序,限制条数

select * from tbase order by (select id from tbase order by random() limit 1);

4)返回结果集的差值

select * from t_except1 except select * from t_except2;

5) 返回结果集的交集

create table t_intersect1(id int,mc text);
insert into t_intersect1 values(1,'tbase'),(2,'tbase');
create table t_intersect2(id int,mc text);
insert into t_intersect2 values(1,'tbase'),(3,'tbase');
select * from t_intersect1 INTERSECT select * from t_intersect2;

6) 合并多个查询结果

--不过虑重复的记录
select * from tbase union all select * from t_appoint_col;
--过虑重复的记录select * from tbase union select * from t_appoint_col; 

7) 查询指定DN上的数据

create table t_direct(id int,mc text);
insert into t_direct values(1,'tbase'),(3,'pgxz');
EXECUTE DIRECT ON (dn001) 'select * from t_direct;';

8) 查询记录所在DN

select xc_node_id,* from t1;
select t1.xc_node_id,pgxc_node.node_name,t1.* from t1,pgxc_node where t1.xc_node_id=pgxc_node.node_id;