1. 程式人生 > >PostgreSQL-9-別名與動態表復制

PostgreSQL-9-別名與動態表復制

註意 employees condition table pri art alter group by 名稱

1、列別名

SELECT column_name AS alias_name FROM table_name conditions... ;

alias_name: 它指定分配給列的臨時名稱

SELECT name,MAX(salary) AS salary_max FROM company3 GROUP BY name; 將salary的最大值設置為別名salary_max

SELECT age,classno,studentname AS n FROM student; 將studentname設置為別名n

2、表別名

SELECT column1, column2.... FROM table_name AS alias_name conditions....;

alias_name:它指定分配給表的臨時名稱。

SELECT e.id,e.name,e.salary,d.dept

FROM employees AS e, department AS d

WHERE e.id = d.id; 這裏設置了company3和department兩個表的別名c和d,簡化代碼

SELECT * FROM employees,department

WHERE employees.id = department.id; 根據字段連接數據

3、動態表復制

\h CREATE TABLE AS

\h CREATE TABLE LIKE

查看語句說明 → 創建表 + 填充表

ALTER TABLE student ADD CONSTRAINT pkey PRIMARY KEY (no); 設置student表格的主鍵

ALTER TABLE student ADD CONSTRAINT agecheck CHECK (age > 0); 設置student表格的CHECK約束

ALTER TABLE student ALTER COLUMN studentname SET NOT NULL; 設置字段非空約束

CREATE TABLE student2 AS SELECT studentname,age FROM student WHERE age <15;

\d student 查看student的表格參數

\d student2 查看student2的表格參數

註意:CREATE TABLE AS復制出來的表,所有約束、註釋和序列都沒有被拷貝,但數據成功拷貝

CREATE TABLE student3 (LIKE student);

SELECT * FROM student3;

\d student 查看student的表格參數

\d student3 查看student2的表格參數

註意:CREATE TABLE LIKE和CREATE TABLE AS不同的是,復制成功拷貝了所有NOT-NULL約束,並且沒有拷貝表數據

PostgreSQL-9-別名與動態表復制