mysql的语法

sql学习网址:http://www.w3school.com.cn/sql/index.asp

1>创建数据库

Create Database if not exists 【myDatabase】;

2>删除数据库

Drop Database if exists 【myDatabase】;

3>创建表 删除表

create table student (id int(5) primary key,name varchar(10) not null,classid int(4));

drop table if exists student

4>给已经存在的表加主键、外键、索引

alter table student add primary key(id);  //加主键索引

alter table student add constraint f_class foreign key(classid) references class(id);  //加外键

alter table student add index(id);   //加一般索引

alter table student add unique(id); //加唯一索引

5>给字段设置自增长(只有int类型的才能设置自增长)

alter table student change id id int auto_increment;

6>追加一个新的字段

alter table class add (sumstu int(2));

7>查看数据库,表结构

show databases; //查看数据有哪些

show tables; //查看有哪些表

show columns from student; //查看改表的列

8>插入数据(insert)

insert into student (name,sex,classid) values("小明","男",1);  //classid是外键关联(此种情况正常插入即可,系统会自动到关联表的主键中查找,如果没有插入失败)

9>更新数据(update)

uodate student set name="小明" where id=1;

10>删除数据(delete)

delete from student where id=1;

11>查询数据(select)

select  * from student;

12>查询过滤重复数据(distinct)

select distinct name from student;

13>limit offset的用法(limit 2 offset 3 从第三条开始查两条  <=> 等价于  limit 3,2)

select  * from class limit 3,2;  <=等价=>  select * from class limit 2 offset 3;

14>查询时where条件like、not like(% 代表任意字符,_代表一个字符)

select * from student where englishname like "_";

select * from student where englishname like "xiao%";

15>查询时where条件IN、not In (in的后面是一个集合)

select  * from student  where

16>查询时where条件between A and B(mysql中返回的结果包括两个边界A和B)

select * from student where id between 1 and 5;

关联查询:表结构

1> 内连接(inner join  <=等价=> join) 后面的条件关键字可以是on 或 where

select c.grade,c.name,s.name,s.sex from class as c inner join student as s where(on) c.id=s.classid;

select c.grade,c.name,s.name,s.sex from class as c join student as s where(on) c.id=s.classid;

2>笛卡儿积 (cross join) 后边不加条件,如果加条件和以上内连接一样的效果

select c.grade,c.name,s.name,s.sex from class as c cross join student as s;

3>外连接的一种-----左连接(left join on) 这里的条件关键字只能用on(亲测):左连接是以左边的表为基准

select c.grade,c.name,s.name,s.sex from class as c left join student as s on c.id=s.classid;

4>外连接的一种-----右连接(right join on) 这里的条件关键字只能用on(亲测): 右连接是以右边的表为基准

select c.grade,c.name,s.name,s.sex from class as c right join student as s on c.id=s.classid;

5>union <=几乎等价=> union all (将两个表的数据结合起来,要求:两个表所查的列数一定要相等)

select name,grade from class union(union all) select name,sex from student;

原文地址:https://www.cnblogs.com/yuxin-555xt/p/6118016.html