mysql

添加路径

export PATH=${PATH}:/usr/local/mysql/bin

手动设置mysql

export MYSQL_HOME=/usr/local/mysql
alias start_mysql='sudo $MYSQL_HOME/bin/mysqld_safe &'
alias stop_mysql='sudo $MYSQL_HOME/bin/mysqladmin shutdown'

连接数据库

mysql -u root -p

数据库

显示所有: show databases;
使用: use <database>;

查看表的字段信息:desc <table>
详细信息: show create table <table>
表字段: show columns from <table>

添加主键约束:alter table 表名 add constraint 主键 (形如:PK_表名) primary key (主键字段);

添加外键约束:alter table 从表 add constraint 外键(形如:FK_从表_主表) foreign key (外键字段) references 主表(主键字段);

删除主键约束:alter table 表名 drop primary key;
删除外键约束:alter table 表名 drop foreign key 外键(区分大小写);

查询外键:
select * from information_schema.key_column_usage  where 
table_schema = 'awesome' and table_name = 'blogs' and referenced_table_name is not null;

mysql安装之后忘记密码

创建基本表

CREATE TABLE IF NOT EXISTS students (
    id INT  NOT NULL AUTO_INCREMENT,
    class_id INT NOT NULL,
    name VARCHAR(32) NOT NULL,
    created_at  BIGINT(20) NOT NULL,
    updated_at  BIGINT(20) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (class_id) REFERENCES class(id)
) ENGINE=InnoDB;

ALTER TABLE students MODIFY created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE students MODIFY updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

数据汇总

avg
count
max
min
sum

//聚合类
默认               avg(all age)
只包含不同值     avg(distinct age)

子句顺序

where group order limit

增加/修改字段注释

alter table test1 modify column field_name int comment '修改后的字段注释'; 

预防sql注入

大小写敏感

  • mysql默认不敏感
  • 建表时设置utf8mb4_bin等 或者查询时使用binary
  • 设置大小写敏感后,查询不区分,可以使用lcase()全小写匹配; 或者使用 COLLATE utf8mb4_general_ci 等
原文地址:https://www.cnblogs.com/jinkspeng/p/5275310.html