常用SQL语句 - 基于MySQL数据库
基础
连接数据库
mysql -h10.20.66.32 -uroot -p123456
-h后面是mysqlServer所在地址,-u后面是用户名,-p后面是密码。
查看数据库
show databases;
使用数据库
use test;
查看表
show tables;
查看表结构
desc winton;
建表
create table t1(
id int not null primary key,
name char(20) not null
);
语法:create table 表名称(字段名 字段名类型 字段描述符, 字段名 字段名类型 字段描述符 );
删除表
drop table test;
语法:drop table 表名称;
修改表
添加字段
alter table t1 add(score int not null);
语法:alter table 秒名称 add(字段名 类型 描述符);
移除字段
alter table t1 drop column score;
语法:alter table 表名称 drop column 字段名, drop column 字段名;
变更字段
alter table t1 change name score int not null;
语法:alter table 表名 change 旧字段名 新字段名 新字段描述符;
插入
全字段插入
insert into winton values(001, 'zzw'), (002,'rss');
语法:insert into 表名 values(字段1值,字段2值,......),(字段1值,字段2值,......);
个别字段插入
insert into winton(id) values(004);
语法:insert into 表名(字段名) values(字段值);
普通查询
单表全字段查询
select * from t1;
语法:select * from 表名;
单表个别字段查询
select id from t1;
语法:select 字段1,字段2,字段3 from 表名;
多表查询
select t1.id,t1.score,winton.name from t1,winton;
语法:select 表1字段,表2字段,表3字段,...... from 表1,表2,表3,.......;
条件查询
单表条件查询
select * from t1 where score>90;
语法:select 字段1,字段2, from 表名 where 条件;
多表条件查询
select t1.id,t1.score,winton.name from t1,winton where t1.id = winton.id;
语法:select 表1字段,表2字段 from 表1,表2 where 条件;
嵌套查询
select name from winton where id=(select id from t1 where score=90);
语法:select 字段1,字段2,...... from 表名 where 条件 (查询);
并查询
(select id from t1) union (select id from winton);
交查询
select id from t1 where t1.id in (select id from winton);
删除
delete from winton where id=4;
语法:delete from 表名 where 条件;
更新
update t1 set score=69 where id=2;
语法:update 表名 set 更改的字段名=值 where 条件;
常用函数
求和
select sum(score) from t1;
注:sum(字段)对字符串和时间无效
求平均值
select avg(score) from t1;
注:avg(字段)对字符串和时间无效
计数
select count(*) from t1;
注:count(字段名)不包含NULL
求最大值
select max(name) from winton;
注:max(column)返回字母序最大的,返回数值最大的
求最小值
select min(name) from winton;
注:min(column)返回字母序最小的,返回数值最小的
常用修饰符
distinct 字段中值唯一
select distinct name from winton;
limit查询结果数限制
select * from winton limit 2;
order by排序
select * from winton order by name;
注:默认是升序
desc降序
select * from winton order by name desc;
asc升序
select * from winton order by name asc;
group by 分组
select name from winton group by name;
索引
创建普通索引
create index wintonIndex on winton (name);
语法:create index 索引名 on 表名 (字段1,字段2,......);
创建唯一索引
create unique index wintonIndex on winton (id);
语法:create unique index 索引名 on 表名 (字段1,字段2,.....);
注:unique index 要求列中数据唯一,不能出现重复
移除索引
drop index wintonIndex on winton;
语法:drop index 索引名 on 表名;