1. 创建数据库:
1)登录bin目录,createdb.exe -U postgres -e mydb;
-U 表示本次操作的登录用户名,如果不写会取windows登录的账户,如Administrator;会提示无创建权限;
2. 登录数据库:
1)用postgre自带的sql shell,登录时选择数据库为创建库
3. CRUD
书写习惯:SQL语句大写,其他小写
3.1)创建表:
CREATE TABLE users( username char(20) PRIMARY KEY, password char(20));
3.2) 插入数据:
INSERT INTO users(username, password) VALUES(‘fredric‘,‘fredric‘),(‘sinny‘,‘sinny‘);
3.4) 查询数据:
SELECT * FROM users;
3.5) 删除数据:
DELETE FROM users WHERE username = "fredric";
4. JOIN
准备:
CREATE TABLE clubs(clubname char(20) PRIMARY KEY, note text);
CREATE TABLE customers( username char(20) PRIMARY KEY, clubname char(20),FOREIGN KEY(clubname) REFERENCES clubs(clubname));
INSERT INTO clubs(clubname, note) VALUES(‘myclub‘,‘good clubs‘);
INSERT INTO clubs(clubname, note) VALUES(‘myclub1‘,‘good clubs‘);
INSERT INTO customers(username, clubname) VALUES(‘fredric‘, ‘myclub‘);
4.1) INNER JOIN
SELECT * FROM clubs INNER JOIN customers ON clubs.clubname = customers.clubname;
返回数据 myclub
4.2) OUTTER JOIN(例如 LEFT JOIN)
SELECT * FROM clubs LEFT JOIN customers ON clubs.clubname = customers.clubname;
返回数据 myclub 和 myclub1
5. 索引
5.1) 创建索引
CREATE INDEX clubs_index ON clubs USING hash(clubname);
CREATE INDEX clubs_index ON clubs USING btree(clubname);//B树类型的索引支持多字段
CREATE UNIQUE INDEX clubs_index ON clubs;//唯一索引,postgre默认在主键上生成唯一索引
5.2) 删除索引
DROP INDEX clubs_index;
6. 聚合函数
6.1) COUNT
SELECT COUNT(*) FROM clubs;
6.2) MIN/MAX
SELECT MIN(clubname) FROM clubs; //输出myclub
SELECT MAX(clubname) FROM clubs; //输出myclub1
7. GROUP BY
SELECT * FROM clubs GROUP By(clubname);
SELECT COUNT(*) FROM clubs GROUP By(note);//1,2
SELECT COUNT(*) FROM clubs GROUP By(note) HAVING COUNT(*) > 1;//2
备注:SQL执行顺序 FROM -> WHERE -> 聚合函数-> GROUP BY -> HAVING -> ORDER BY -> SELECT;
8. 事务
BEGIN TRANSACTION;
DELETE FROM customers WHERE clubname = ‘myclub‘;
DELETE FROM clubs WHERE clubname = ‘myclub‘;
COMMIT; //执行删除
ROLLBACK; //回滚操作
SAVEPOINT;为保存点,回滚的位置
例如:
SAVEPOINT mypoint;
ROLLBACK TO mypoint;