数据库管理

— 查看、创建、进入数据库

MySQL

系统命令

  1. > mysql -u root -p

SQL语句

  1. SHOW DATABASES;
  2. CREATE DATABASE mydb;
  3. USE mydb;

PgSQL

系统命令

  1. => sudo su postgres
  2. => psql -l
  3. => createdb mydb
  4. => psql mydb
  5. # 查看当前数据库
  6. =>\c mydb

SQL语句

  1. CREATE DATABASE my_pg
  2. WITH OWNER = my_pg
  3. ENCODING = 'UTF8'
  4. TABLESPACE = tbs;

数据表

— 创建、查看数据表及信息

MySQL

deeprdraw_order.sql

  1. -- 创建数据表
  2. CREATE TABLE users o(
  3. id INT AUTO_INCREMENT,
  4. name VARCHAR(255) NOT NULL
  5. );
  6. -- 查看数据表
  7. SHOW TABLES;
  8. -- 查看表信息
  9. SHOW COLUMNS FROM users o;
  • 另外,mysql也有information_schema

    PgSQL

    系统命令 ```shell

    查看数据表

    => \dt => \d+ orders* 或 psql -d bench -c “\dt”

查看表信息

=> \d users

  1. sql语句
  2. ```sql
  3. -- 查看数据表
  4. select * from pg_tables;
  5. -- 创建数据表
  6. CREATE TABLE users o(
  7. id SERIAL,
  8. name VARCHAR(255) NOT NULL
  9. );

为查询columns创建视图

  1. SELECT *
  2. FROM information_schema.columns
  3. WHERE table_schema = 'public'
  4. AND table_name = 'user'
  5. ORDER BY column_name ASC;
  6. -- 创建视图
  7. CREATE view user_columns
  8. as
  9. SELECT *
  10. FROM information_schema.columns
  11. WHERE table_schema = 'public'
  12. AND table_name = 'user'
  13. ORDER BY column_name ASC;
  14. SELECT * FROM user_columns;

导入SQL

MySQL

  1. > source /db/users/o.sql

PgSQL

  1. => \i /db/users/o.sql

数据类型

javapoint: sql-data-types
MySQL和PostgreSql对照 - 图1

表约束

关键字

MySQL和PgSQL具有相同的sql约束

  • not null: 不能为空
  • unique: 在所有数据中值必须唯一
  • check: 字段设置条件
  • default: 字段默认值
  • primary key: 主键,不能为空,且不能重复
    1. create table public.test (
    2. id SERIAL,
    3. name VARCHAR(10) not null unique,
    4. age integer not null default 20,
    5. check (age > 1),
    6. primary key(id)
    7. );

    修改主键

    1. alter table sample_details drop primary key;
    2. alter table sample_details add primary key(sample_no asc, sku_no asc);

    增删改字段

    ```sql alter table users add fullname varchar(255); alter table users drop fullname;

— 重命名字段 rename to — MySQL alter table users CHANGE player nba_player VARCHAR(255) — PgSQL alter table users rename player to nba_player;

— 修改字段类型 — MySQL alter table users MODIFY nba_player VARCHAR(100); — PgSQL alter table users alter nba_player type varchar(100);

  1. <a name="66805fe0"></a>
  2. # INSERT语句
  3. - insert into [tablename] (field, ...) values (value, ...)
  4. ```sql
  5. -- 选择字段插入
  6. insert into user (username, password, email) VALUES ( 'a', 'b', 'c');
  7. -- 全字段插入
  8. insert into user VALUES (DEFAULT, 'a', 'b', 'c');

SELECT语句

  1. -- MySQL
  2. SELECT * FROM users 3, 6;
  3. -- PgSQL
  4. select * from users limit 6 offset 3;

WHERE

  1. --- 1=1便于增减AND条件
  2. SELECT * FROM users
  3. WHERE 1 = 1
  4. AND gender = 0;
  5. -- 1=2,只看表结构
  6. SELECT * FROM users WHERE 1 = 2;

UPDATE

  • update [table] set [field=newvalue,…] where …

DELETE

  • delete from [table] where …

TRUNCATE

  1. -- pgsql
  2. TRUNCATE [ TABLE ] [ ONLY ] name [ * ] [, ... ]
  3. [ RESTART IDENTITY | CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]

copy

  1. --mysql
  2. -- 只复制表结构,方法1
  3. CREATE TABLE new_table_name LIKE source_table_name;
  4. -- 只复制表结构,方法2
  5. -- 复制表结构和数据
  6. CREATE TABLE order_archived AS
  7. SELECT * FROM orders;
  8. -- 利用tmp
  9. SELECT tmp.name FROM (
  10. SELECT name FROM student_contacts GROUP BY name HAVING COUNT(1) > 1
  11. ) AS tmp;
  12. -- truncate table
  13. INSERT INTO order_archived
  14. SELECT * FROM orders
  15. WHERE order_date < '2019-01-01';
  16. -- pgsql本地文件copy
  17. COPY table_name [ ( column_name [, ...] ) ]
  18. FROM { 'filename' | PROGRAM 'command' | STDIN }
  19. [ [ WITH ] ( option [, ...] ) ]
  20. COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
  21. TO { 'filename' | PROGRAM 'command' | STDOUT }
  22. [ [ WITH ] ( option [, ...] ) ]
  23. \copy (select user_id, pay_money, create_date + 31 as create_date from t_pay_202012) to '/home/zhangsan/database/pgsql/202101.txt';

聚合

distinctsummaxmingroup bygroup by+having

  1. select distinct team from users;
  2. select sum(score) from users;
  3. select max(score) from users;
  4. select min(score) from users;
  5. select * from users where score = (select max(score) from users);
  6. select team, max(score) from users group by team;
  7. select team, max(score) from users group by team having max(score) >= 25 order by max(score);

优先顺序:where>group by>having>order by
WHERE 和 HAVING、ON 有什么区别?

函数

  1. select player, length(player) from users;
  2. select player, concat(player, '/', team) as "球员信息" from users;
  3. select substring(team, 1, 1) as "球队首文字" from users;
  4. select concat('我', substring(team, 1, 1)) as "球队首文字" from users;
  5. select random();
  6. select * from users order by random();
  7. select * from users order by random() limit 1;
  1. SELECT SUSER_NAME(); -- SYBASE, 数据库登录用户名

Date function

  1. -- SQL SERVER/ SYBASE
  2. SELECT DATEDIFF(day, '2020-03-25 23:59', GETDATE()) AS difference_in_day;
  3. SELECT convert(datetime, convert(char(20), dateadd(dd, 3, getdate()), 1))
  4. -- MYSQL
  5. SELECT NOW() - INTERVAL 1 DAY;
  6. SELECT DATE_ADD(NOW(), INTERVAL -1 DAY);
  7. SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);
  8. SELECT YEAR(NOW());

索引

  1. -- PGMySQL通用
  2. -- 创建索引
  3. -- 索引:根据该字段查询更快,追加数据时变慢
  4. > create index nba_player_index on users(nba_player);
  5. > ALTER TABLE users ADD index nba_player_index (nba_player);
  6. -- 去掉索引
  7. > drop index nba_player_index on users;
  8. > ALTER TABLE users DROP INDEX nba_player;

索引

Join连接

  1. -- 内连接:MySQL&PgSQL
  2. SELECT u.player, t.content FROM users u JOIN twitters t ON u.id = t.user_id WHERE u.id = 1;
  3. -- 外连接:MySQL
  4. SELECT u.player, t.content FROM users u LEFT JOIN twitters t ON u.id = t.user_id WHERE u.id = 1;
  5. SELECT u.player, t.content FROM users u RIGHT JOIN twitters t ON u.id = t.user_id WHERE u.id = 1;
  6. -- 外连接:PgSQL
  7. SELECT u.player, t.content FROM users u LEFT OUTER JOIN twitters t ON u.id = t.user_id WHERE u.id = 1;
  8. SELECT u.player, t.content FROM users u RIGHT OUTER JOIN twitters t ON u.id = t.user_id WHERE u.id = 1;

外键

  1. -- MySql
  2. ALTER TABLE order_account add CONSTRAINT `FK_order_account_agent` FOREIGN KEY (`agent_id`) REFERENCES `agent` (`id`);

视图

  1. create view curry_twitters as select u.player, t.content from users as u, twitters as t where u.id = t.user_id and u.id = 1;
  2. -- 查看已有视图
  3. -- MySQL
  4. SHOW TABLE STATUS WHERE COMMENT='view';
  5. -- PgSQL
  6. > \dv
  7. > \d curry_twitters
  8. >select * from curry_twitters;
  9. -- 删除视图
  10. > drop view curry_twitters;

使用事务

数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。 事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据的资源。通过将一组相关操作组合为一个要么全部成功要么全部失败的单元,可以简化错误恢复并使应用程序更加可靠。一个逻辑工作单元要成为事务,必须满足所谓的ACID(原子性、一致性、隔离性和持久性)属性。事务是数据库运行中的逻辑工作单位,由DBMS中的事务管理子系统负责事务的处理。

  • PostgreSql数据库事务使用
    • begin
    • commit
    • rollback
  1. > select * from users;
  2. > begin;
  3. > update users set score = 50 where player = '库里';
  4. > update users set score = 60 where player = '哈登';
  5. > commit;
  6. > select * from users;
  7. > begin;
  8. > update users set score = 0 where player = '库里';
  9. > update users set score = 0 where player = '哈登';
  10. -- 如果在这里执行了一下SELECT,还是会生效。
  11. > rollback;
  12. > select * from users;