mysql增删改查练习

时间:2021-01-16 23:28:20

Mysql增删改查sql语句练习

关于数据库的一些操作:

进入mysql 命令行: mysql -uroot –p

查看所有数据库: show databases;

创建数据库: create database wg charset utf8;

删除数据库: drop database wg;

选择数据库: use databases;

查看所有表: show tables;

查看创建数据库的语句:show create database databasename;

查看创建表的语句:show create table tablename;

查看表结构:desc tablename;

增:

mysql> use wg;

mysql> create table students( id int auto_increment primary key,name varchar(10) not null,sex varchar(12),address varchar(50),phone int not null unique);

#自增长 auto_increment

#非空 not null

#默认值 default 'xx'

#唯一 unique

#指定字符集 charset

#主键 primary key

mysql> create table scores(id int auto_increment primary key,s_id int not null,grade float not null);

数据

mysql> insert into  student (id,name,sex,phone)  values(122,’wg’,’男’,’110’);

mysql> insert into students values(111,’wg’,’121’,’dd’) ;

mysql> drop table tablename;

mysql> truncate  tablename; 快速删除表数据,自增长id从头在来,快速,从磁盘直接删除,不可恢复

mysql> delete  from  student; 删除整个表的数据,自增长继续

mysql> alter table oldtable rename newtable; 改表名

mysql> alter table scores modify s_id varchar(20);

mysql> alter table scores change s_id scoresss varchar(16); 修改表结构

mysql> alter table scores add age float after id; 新增字段的位置(age放在了ID后面)

mysql> update student set age=18;不指定条件,修改所有

mysql> update student set age=18 where name=‘wg’;只修改网工

查:

mysql> show create table tablename; 查看新建表语句

mysql> desc   tablename; 查看表结构

mysql> show tables; 查看所有表

mysql> select * from students limit 5;查询5条

mysql> select * from students limit 1,5;从第几条开始,下面的n条

mysql> SELECT * from students where sex='男'; #指定条件

mysql> SELECT * from students where sex='男' and age>10; #多个条件,必须同时满足

mysql> SELECT * from students where sex='男' or sex='未知' ; #多个条件,有一个满足即可

mysql> SELECT * from students where sex !='男'; #<>也是不等于

mysql> SELECT * FROM students where addr like '%东京%';#模糊匹配,%代表的是通配符,必须得用like

mysql> SELECT * from students a where a.stu_name like '姚_';#_通配符表示任意一个单字符,姚字后面只能跟一个字

mysql> SELECT a.stu_name '学生名称',a.phone '学生电话' from students as a where a.stu_name='姚远';#给表起别名,as可以省略

SELECT * from students a where a.money BETWEEN 1000 and 10000;#在什么什么之间的数据

SELECT * from students ORDER BY money desc; #order by xxx desc,根据哪个字段继续排序,默认是升序,降序是desc,升序asc

SELECT * from students a where a.addr = '' or a.addr is null; #查询字段为空的数据

SELECT DISTINCT a.money from students a ;#去重

SELECT COUNT(*) '学生人数' from students where sex='女'; #统计行数

SELECT MAX(a.money) 钱最多 from students a; #最大值

SELECT min(money) 钱最少 from students;#最小值

SELECT AVG(a.money) 平均多少钱 from students a; #平均数

SELECT sum(a.money) 总共多少钱 from students a;#总和

备份数据库:

# mysqldump -uroot -p123456 db > db.sql

# mysqldump -uroot -p123456 -A > all.sql

恢复数据:

mysql -uroot -p123456 db < db.sql