您的位置:首页 > 数据库 > MySQL

MySQL基本语法操作,对表的基本操作,查询

2018-05-30 10:10 369 查看

对表的基本操作

1.使用主键约束

在字段后面加上 primary key
或者 primary key(name)
2.contraint  约束名 foreign key () references 表名(主键)
3.唯一属性 unique 
4.非空属性 not null
5.默认属性 default
6.设置自动增加 auto_increment
7.查看数据表结构
DESC 表名 
查看表详细结构
show create 表名
8.修改表名
alter table 表名 remove 新表名
9.修改字段的数据类型,也可修改排列位置
alter table 表名 Modify 字段名 <数据类型> 
10.修改字段名 
alter table 表名 change 旧字段名 新字段名 <数据类型>
11.添加字段
alter table 表名 add 字段名 <数据类型> alter 字段名|first
12.删除字段
alter table 表名 drop 字段名
13.删除数据表
drop table if exists 表名
注意:其他表对该表有外键约束时,要先删除外键
14.删除外键约束

alter table 表名 foreign key 外键约束名

查询

1、查询所有字段
select * from 表名
2、查询多个字段
select 字段1,字段2 from 表名
3、查询指定记录
select  字段1,字段2,字段3 from表名
where 条件 
where 字段名 in(),和or的功能一样,但是in()执行速度要高于or
where 字段名 between 0 and 1
where 字段名 like 'b%' 以b开头
where 字段名 like '%b%' 包含b
where 字段名 like 'b%y' b开头y结尾
where 字段名 like 'b_' b开头,俩字符,‘_’代表单个字符
4、查询结果不重复
select distinct 字段1,字段2 from 表名
5、对查询结果进行排序
select 字段1,字段2,字段3 from 表名
order by 字段1,字段2   ;
先对字段1进行排序,如果相同再对字段2进行排序
DESC降序 ASC升序 默认为升序
6、创建分组
select id,count(*) as total 
from 表名 
group by id with roolup;
count():用来对分组后计数
group_concat()查询分组后的名称
sum():求总和
avg():求平均数
max():求最大值
min():求最小值
having分组后过滤,where分组前过滤
roolup与group by互相排斥




连接查询:
1、内连接查询
 
select 字段1,字段2,字段3
from 表1,表2
where 表1.id=表2.id


select id,字段2,字段3
from 表1 inner join 表2
on 表1.id=表2.id


2、自连接查询
select S1.字段1,S2.字段2
from student AS S1,student AS S2
where 表1.id=表2.id  




3、外链接查询
left join 返回左表中的所有值
right join 返回右表中的所有值


4、子查询
带any() ,some()  满足任意条件返回查询值
select id from student 
where id >any(子查询)


all() 满足所有条件


where exists(子查询)
如果子查询有值 则进行外层查询
where not exists(子查询)
如果子查询无结果 则进行外层查询


where in (子查询)


5、合并查询结果
select 字段1,字段2,字段3
from 表名
where 条件


UNION ALL


select 字段1,字段2,字段3
from 表名
where 条件;

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: