sql常用操作
cmd窗口登录MySQL
mysql -u root -p //回车输入密码
创建数据库
creat database 库名;
查询数据库
show databses;
使用数据库
use 库名;
查看数据库包含的表
show tables;
创建一个表
create table table_name( id int(12) primary key , name varchar(20))
显示创建表的语句
show create table 表名;
插入数据
insert into table_name(key1,key2,key3) values(value1,value2,value3); insert into 表名(字段1,字段2,字段3)values(value1,value2,value3),(value1,value2,value3),(value1,value2,value3); //插入多条数据
修改数据
update table_name set key1=value1,key2=value2 where key3=value3;
删除数据
delete from table_name where key=value;
查询数据
select * from 表名;
select name,sex from 表名 where id=1;select id,name from 表名 where id between 1 and 9 order by id desc;
select * from 表名 where 字段1 like '张%';查询字段1值以张开头的
select * from 表名 where 字段1 like '%三'; 查询字段1值以三结尾的
select * from 表名 where 字段1 like '%张%'; 字段含有张的
分组函数
count avg sum max min
select count(*) from table_name; //查询表中有多少条数据 select count(字段) from table_name; //取得字段不为null 的条数 select sum(字段名) from table_name; select sum(字段名+IFNULL(comm,0)) from table_name; select avg(字段) from table_name; select max(字段名) from table_name; select min(字段名) from table_name;
多表查询
--内连接 select a.字段1,b.字段2 from 表a,表b where a.字段3=b.字段3; 一定要写查询条件,否则会出现笛卡尔效应 --自连接 select a.字段1,b.字段2 from 表C a, 表C b where a.字段m=b.字段n; 把一张表看成两张表 --左连接 select a.字段1,b.字段2 from A表 a left join B表 b on a.字段m=b.字段m 以左边的表为基准和右边的表比较, 右连接
表复制
create table new表名 as select * from old表名; insert into new表名 select * from old表名 where条件;
修改表结构操作
--增加表字段 alter table 表名 add(phonenum varchar(20)); --修改表字段长度 alter table 表名 modify phonenum varchar(30); --修改表字段名称 alter table 表名 change old字段名 new字段名 char(2); --删除字段值 alter table 表名 drop 字段名称;