mysql常用语句整理

昨天做了个BIGO的笔试,发现考的很多SQL语句我都有点模糊。想把这些常用的常考的sql语句做一下整理。还是那种感觉,更多东西你好像懵懵懂懂的知道,但是实际问到了让你手撕代码又很虚,还是要注重基础及整理啊。任重道远,加油!!

MySQL常用命令

create database name; 创建数据库

use database name; 选择数据库

drop database name 直接删除数据库,不提醒

show tables; 显示表

describe table name; 表的详细描述

select中加上distinct去除重复字段

说明:几个简单的基本的sql语句

选择:select * from table1 where 范围

插入:insert into table1(field1,field2) values(value1,value2)

删除:delete from table1 where 范围

更新:update table1 set field1=value1 where 范围

查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!

排序:select * from table1 order by field1,field2 desc

总数:select count as totalcount from table1

求和:select sum(field1) as sumvalue from table1

平均:select avg(field1) as avgvalue from table1

最大:select max(field1) as maxvalue from table1

最小:select min(field1) as minvalue from table1


增加一个列:Alter table tabname add column col type

添加主键: Alter table tabname add primary key(col)

创建索引:create [unique] index idxname on tabname(col….)    注:索引是不可更改的,想更改必须删除重新建。




#创建表create table student(

id int auto_increment primary key,

name varchar(50),

sex varchar(20),

date varchar(50),

content varchar(100)

)default charset=utf8;

#查看表的结构

describe student;  #可以简写为desc student;

#插入数据

insert into student values(null,'aa','','1988-10-2','......');

insert into student values(null,'bb','','1889-03-6','......');

insert into student values(null,'cc','','1889-08-8','......');

insert into student values(null,'dd','','1889-12-8','......');

insert into student values(null,'ee','','1889-09-6','......');

insert into student values(null,'ff','null','1889-09-6','......');

#查询表中的数据select * from student;select id,name from student;

#修改某一条数据update student set sex='' where id=4;

#删除数据delete from student where id=5;

# and

select * from student where date>'1988-1-2' and date<'1988-12-1';

# or

select * from student where date<'1988-11-2' or date>'1988-12-1';

  

#between

select * from student where date between '1988-1-2' and '1988-12-1';

#in

查询制定集合内的数据select * from student where id in (1,3,5);

#排序 asc 升序  desc 降序

select * from student order by id asc;

#分组查询 #聚合函数

select max(id),name,sex from student group by sex;

 select min(date) from student;

 select avg(id) as '求平均' from student;

 select count(*) from student;   #统计表中总数

 select count(sex) from student;   #统计表中性别总数  若有一条数据中sex为空的话,就不予以统计~

 select sum(id) from student;

#查询第i条以后到第j条的数据(不包括第i)

select * from student limit 2,5;  #显示3-5条数据

#巩固练习

create table c(

 id int primary key auto_increment,

 name varchar(10) not null,

 sex varchar(50) ,  #DEFAULT '' ,

 age int unsigned, #不能为负值(如为负值 则默认为0)

 sno int unique    #不可重复

);


猜你喜欢

转载自blog.csdn.net/zhouboke/article/details/80523883