天天看點

GaussDB(DWS)資料庫入門文法

1、連接配接
	gsql -h 17.244.110.231 -p 25108 -d dlp_db -U dlp  -W  1234@    登入
	
2、編碼	
	show server_encoding;  檢視目前資料庫編碼  
	
3、搜尋路徑	
	show search_path;  檢視模式搜尋路徑,無論如何搜尋路徑前兩個一定是pg_temp和pg_catalog
	set search_path to my_schema,public; 将my_schema,public兩個模式加入搜尋路徑
	
4、模式
	select current_schema; 檢視資料庫目前模式 
	set current_schema=my_schema;  設定目前資料庫模式。
	\dn          檢視所有模式及其所有者 	
	create schema my_schema authorization dlpuser; 建立schema并指定owner
	 使用者隻能通路屬于自己schema中的資料庫對象,若要通路其他人的schema中資料庫對象則必須具有該schema的usage權限。
	
5、使用者	
	select * from pg_user;  檢視目前資料庫使用者 
	create user joe with password '123456';
	
6、資料庫
	select datname from pg_database; 檢視資料庫清單
	create database my_database template template0; 參考template0建立資料庫(預設template1)
	
7、表	
	select * from pg_tables;  檢視目前資料庫擁有的表
	select * from dba_tab_partitions;  檢視目前資料庫擁有的分區表
	\d+ my_schema.t_emp;  檢視表的屬性
	select * from my_schema.t_emp_partition partition(p1);  檢視分區表P1分區資料
	
	create table my_schema.t_emp(id int)  --可以set current_schema來指定schema.不指定schema預設使用public模式
		with(orientation=column,compression=middle) --指定列存和壓縮級别
		distribute by hash(id);  --指定分布方式,也可以是replication\round robin(僅适用于外表)
			--未指定分布列,系統會自動選擇一個類型符合要求的作為分布列。
	
8、視圖	
	select * from dba_views; 檢視所有視圖
	select * from user_views; 檢視目前使用者下的視圖
	\d+ my_schema.my_view;  檢視視圖的屬性
	create or replace view my_view select * from t1;
	
9、索引	
	select relname from pg_class where relkind='i';  檢視系統和使用者定義的所有索引
	\di+ my_schema.my_index;  檢視索引的屬性
	create index my_index on my_schema.t_emp(id);   建立索引,可以多個字段,逗号分隔
	可以建立索引的列:
		1、經常查詢的。
		2、主鍵列。 
		3、連接配接列。
		4、過濾列。
		5、排序列。
		6、分組列。
		7、去重列。
	如果使用索引比使用順序查詢更快,就會自動使用索引。 
	
10、序列
	序列sequence自增不重複,是以常用作主鍵。 
	create table t1(id serial);   serial為4位元組序列整型,背景會自動建立并維護一個序列。 
 先建立序列再使用序列:
	create sequence seq [cache 100]; cache慎用,否則序列可能不連貫自增
	create table t2(id int default nextval('seq'));
	alter sequence seq owned by t2.id; 将字段和序列關聯,删除字段或表序列也删除
	
	每一次新的序列值的産生都由GTM維護,GTM作為全局唯一節點,可能存在性能瓶頸。
	多節點下隻有GTM上和最近更新序列值的節點上的序列值是最新的。