MySQL操作语法整理

-------基础操作-------

增:

数据库   create database ***;  #MySQL5.0.2之后,等价于create schema ***;

表   create table ***;

字段   alter table *** add column *** type; #有没有column 都可以/ alter table *** add (*** type);

主键   alter table *** add primary key ***;

数据   insert into ***(字段1,字段2……) values(字段1的值,字段2的值);

 

删:

数据库   drop database ***;

表   drop table  ***;

表的数据非结构  truncate table ***;

字段   alter table *** drop column ***;

主键   alter table *** drop primary key ***;

数据   delete from *** where 字段1=***;

 

改:

表 alter table *** rename to ***;

字段名 alter table *** change columnname1  columnname2 varchar(50);

字段属性 alter table *** modify columnname char(20) not null;

数据 update *** set columnname1=*** where columnname2=***;

 

查:

数据

select * from *** ;

select * from *** where columnname= *** order by columnname2 desc;

 


-------实例练习-------

#显示数据库
show databases;

#创建数据库
create database db1;

#删除数据库
drop database db1;

#使用该数据库
use db1;

#显示数据库中的表
show tables;

#先判断表是否存在,存在先删除
drop table if exists student;

#创建表
create table student(
id int auto_increment primary key,
name varchar(50),
sex varchar(20),
date varchar(50),
content varchar(100)
)default charset=utf8;

#删除表
drop table student;

#查看表的结构
describe 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);

#order by 排序, asc 升序  desc 降序
select * from student order by id asc;

#group by分组查询 
select max(id),name,sex from student group by sex;

select min(date) from student;

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

#count统计数量

select count(*) from student;   #统计全体数据总量

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

#sum、max、min、 avg基础运算

select sum(id) from student;

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

select min(date) from student;

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

#查询第i条以后到第j条的数据(不包括第i条)
select * from student limit 2,5;  #显示3-5条数据

#查询不重复值

select distinct education from zhaopin;

#表连接,数据库中的表可通过相同的主键将彼此联系起来

select student.class,student.name,scholarship.amount

from student

inner join scholarship

on student.id_s=scholarship.id_s

order by student.class;   #通过id_s学号这个相同的主键,将学生信息与得奖学金的信息表连接在一起


join的语法关系如下:

MySQL操作语法整理_第1张图片

(图片来源于网络)

你可能感兴趣的:(数据库,数据库)