启动 PostgreSQL 服务器:sudo service postgresql start
停止 PostgreSQL 服务器:sudo service postgresql stop
重启 PostgreSQL 服务器:sudo service postgresql restart
查看 PostgreSQL 服务器状态:sudo service postgresql status
进入 psql 控制台:psql
退出 psql 控制台:\q
切换到某个数据库:\c dbname
显示所有数据库:\l
创建数据库:createdb dbname
删除数据库:dropdb dbname
备份数据库:pg_dump dbname > backup.sql
恢复数据库:psql dbname < backup.sql
显示所有表:\dt
创建表:CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype);
查看表结构:\d table_name
添加列:ALTER TABLE table_name ADD COLUMN column_name datatype;
修改列数据类型:ALTER TABLE table_name ALTER COLUMN column_name TYPE datatype;
删除列:ALTER TABLE table_name DROP COLUMN column_name;
添加主键:ALTER TABLE table_name ADD CONSTRAINT pk_constraint PRIMARY KEY (column_name);
添加外键:
ALTER TABLE child_table ADD CONSTRAINT fk_constraint FOREIGN KEY (column_name) REFERENCES parent_table (column_name);
删除约束:ALTER TABLE table_name DROP CONSTRAINT constraint_name;
插入数据:INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3);
更新数据:UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
删除数据:DELETE FROM table_name WHERE condition;
查询数据:SELECT column1, column2 FROM table_name WHERE condition;
模糊查询:SELECT * FROM table_name WHERE column_name LIKE 'value%';
分组查询:SELECT column1, COUNT(column2) FROM table_name GROUP BY column1;
连接查询: SELECT t1.column1, t2.column2 FROM table1 t1 INNER JOIN table2 t2 ON t1.column1 = t2.column1;
子查询:SELECT column1 FROM table_name WHERE column2 = (SELECT MAX(column2) FROM table_name);
排序:SELECT * FROM table_name ORDER BY column_name [ASC | DESC];
限制返回结果行数:SELECT * FROM table_name LIMIT number_of_rows;
跳过前几条记录:SELECT * FROM table_name OFFSET number_of_rows;
计算列的平均值:SELECT AVG(column_name) FROM table_name;
计算列的最大值:SELECT MAX(column_name) FROM table_name;
计算列的最小值:SELECT MIN(column_name) FROM table_name;
计算列的总和:SELECT SUM(column_name) FROM table_name;
计算行数:SELECT COUNT(*) FROM table_name;
事务处理:BEGIN; -- SQL statements COMMIT;
回滚事务:ROLLBACK;
为用户添加权限: GRANT privilege_name ON table_name TO user_name; GRANT ALL PRIVILEGES ON table_name TO user_name;
删除用户权限:REVOKE privilege_name ON table_name FROM user_name;
创建用户:CREATE USER user_name WITH PASSWORD 'password';
修改用户密码:ALTER USER user_name WITH PASSWORD 'new_password';
删除用户:DROP USER user_name;
更改数据库所有者:ALTER DATABASE dbname OWNER TO user_name;
创建扩展:CREATE EXTENSION extension_name;
查看已安装的扩展:\dx
卸载扩展:DROP EXTENSION extension_name;
查看 pg_hba.conf 文件路径:SHOW hba_file;
查看 postgresql.conf 文件路径:SHOW config_file;
以上是更多 PostgreSQL 常用命令方面的参考,希望对你有所帮助。
上一篇:Mysql 数据备份(详细教程)