mysql命令行常用命令笔记

mysqltest

1.登陆数据库
  • 连接本地mysql数据库 mysql -u用户名 -p

  • 连接其他电脑上的mysql数据库 mysql -u用户名 -p -hIP地址 -port端口

2.展示当前mysql中所有数据库
show databases;

  

3.创建数据库
create database testDB;

  

4.进入/切换 数据库中

use 数据库名;

use testDB;

  

5.可以开始操作数据库表。
create table t1(
   num int(4) unsigned zerofill
);
insert into t1 values(18);
insert into t1 values(1.8);
insert into t1 values(1.1);
insert into t1 values(-1);
select * from t1;
create table t2(
    money double(4,2) zerofill
);
insert into t2 values(3.1415926);
insert into t2 values(123.1415926); //error 超出了有效位数
select * from t2;
create table t3(
    birthday date
);
insert into t3 values("2020-9-11");
select * from t3;
​
create table t4(
    sex enum('男','女')
);
insert into t4 values("女");

  

6.查看当前数据库中的所有数据库表
show tables;

  

7.DDL语句
1)建表语句:
create table 表名()engine= Innodb default charset=utf8;
注:engine 用来指定数据库引擎;
   defualt charset 用来指定当前表中默认编码。
​
2)删除表:
    drop table 表名,表名...
​
create table t5(
    id int
);
drop table t5;

  

8.数据库表和表的关联关系

一对一:外键放到任意一方 一对多:外键放到多的一方 多对多:需要通过桥表来表示关联关系

9.mysql数据库中自增长的写法
create table auto_test(
    id int auto_increment,
    name varchar(20) not null,
    primary key(id)
);
insert into auto_test(name) values("tom");
​
show variables like '%increment%';
set auto_increment_increment=2;自增长为2;
show session variables like '%increment%';
show global variables like '%increment%';
​
set global auto_increment_offset=3;
注:设置值时,最大值为65535,最小值为1

  

10.index索引

作用:用来提高检索效率。

create table index_test(
    id int primary key auto_increment,
    name varchar(20),
    age int,
    index name_index(name),
    key(age)
);
CREATE INDEX indexName ON table_name (column_name);
ALTER table tableName ADD INDEX indexName(columnName);
​
select * from index_test;  查询效率不变
select name,age,id from index_test; 查询效率提高
将来只有通过添加索引列进行查询才会提高效率。
drop index 删除索引
drop index name_index and index_test;

  

11.修改表中的相关内容
create table alter_test(
    id int primary key auto_increment,
    name varchar(10)
    );
添加列 alter table alert_test add column phone int unique; 
修改表名 alter table alert_test rename alter_test;
修改列名 alter table alter_test change phone num int(5) not null;
删除表的主键约束(注意不能设置自增长 否则无法删除) 
    alter table alter_test drop primary key(id);
    ALTER TABLE testalter_tbl DROP PRIMARY KEY;
给表添加主键约束
    alter table alter_test add primary key(id);
删除列 alter table alter_test drop column name;e

  

12.DML
. 1)insert
语法:
     insert into 表名 values(值,值.....);
     insert into 表名 (字段名,字段名....) values(值,值.....);
插入数据时,默认按照表声明的字段顺序插入

  

. 2) delete
语法:
     delete from 表名; 删除整张表,复制一个空表
     delete from 表名 where 条件 limit 数字;

  

. 3) update
语法:
     update 表名 set 列名=新值,列名=新值 ..... where 条件;

  

. 4) Optimize table
语法:
     optimize table 表名;      回收闲置的空间

  

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-10-10 20:12  Mark_code  阅读(88)  评论(0)    收藏  举报