PostgreSQL-9-别名与动态表复制
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约束,并且没有拷贝表数据