SQL基础语句

库相关操作

cmd窗口登录MySQL,连接数据库
mysql -u root -p  --回车输入密码

创建数据库

creat database 库名;

查询数据库

show databses;

使用数据库

use 库名;

查看数据库包含的表

show tables;

删除数据库

drop database 数据库名

 

表结构操作

建表

create table 表名称( 字段名 字段名类型 字段描述符,字段名 字段类型 字段描述符);
create table table_name( 
  id int(12) primary key ,
  name varchar(20)
);

 显示建表语句

show create table 表名;

查看表结构

desc table_name;

修改表结构操作

--增加表字段
alter table 表名 add(phonenum varchar(20));
--修改表字段长度
alter table 表名 modify phonenum varchar(30);
--修改表字段名称
alter table 表名 change old字段名 new字段名 char(2);
--删除字段值
alter table 表名 drop 字段名称;

 删除表

drop table  table_name;   /*删除表(整张表)*/

 

表数据操作

插入数据

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 table_name;
select name,sex from table_name where id=1;
select id,name from table_name where id between 1 and 9 order by id descselect * from table_name where some_key like '张%'; --查询字段1值以张开头的
select * from table_name where some_key like '%三';  --查询字段1值以三结尾的
select * from table_name where some_key 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 表a,表b where a.字段m=b.字段n; 把一张表看成两张表

--左连接left join
结果集保留左表的所有行,但只包含第二个表与第一表匹配的行。第二个表相应的空行被放入NULL值
select a.字段1,b.字段2 from A表 a left join B表 b on a.字段m=b.字段m

--右连接RIGHT JOIN(right outer join)右外连接(右连接)
右外连接保留了第二个表的所有行,但只包含第一个表与第二个表匹配的行。第一个表相应空行被入NULL值。

--全连接。会把两个表所有的行都显示在结果表中

表复制

create table new表名 as select * from old表名;  --创建一个新表并把旧表数据导入
insert into new表名 select * from old表名 where条件; --将旧表查询的数据插入到新表(新表已建好)中

 

posted @ 2020-05-28 21:08  乔乔新  阅读(150)  评论(0)    收藏  举报