基础的sql语句

1.创建数据库\表

  create database 库名;\ create table 表名(列1  类型  primary key not null   ,列2 类型 not null  ,.....);

2.展示所有已存在的数据库

  show databases;\show tables;

3.进入指定的数据库

   use 库名;

4.查询表数据

 select * from 表名 where 范围;

5.插入表数据

 insert into 表名(列1,列2,...)values (value1,value2,....);

6.更改表数据

 update 表名 set 列名=新值 where 列名=旧值;

7.删除表数据

 delete from 表名 where 范围;

8.用已有的表创建新表

 create table 新表 like 旧表; /新表展示的列名和旧表完全一致,只是无数据

9.增加表的列/主键

 alter table 表名 add column 列名 类型 primary key ; /列增加后将不能删除。列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

10.增加/删除表的主键

alter  table 表名 add/drop primary key(列名);

11.删除数据库/表结构

drop database 库名/table 表名; 

12.重点注意的sql语句

查找:select * from table1 where field1 like ’%value1%’
排序:select * from table1 order by field1,field2 [desc]   / desc是降序,asc是升序,一般默认就是升序
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1

13.高级查询运算词

union:返回两个结果集的并集,如

 select name from a

 union

 select name from b;  \得出的结果是a表和b表的name并集,删除重复行,默认排序

注意:union all 则是不删除重复行全部都展示,且没有排序

except:返回只在第一个结果集而不在第二个结果集中的数据,如

 select name from a

 except

 select name from b; \展示a表存在而b表不存在的数据,删除重复行

注意:except all 多了不删除重复行全部都展示

intersect:返回两个结果集的交集,如

 select name from a

intersect 

 select name from b; \展示a表和b表都存在的数据,删除重复行

注意:intersect all 多了不删除重复行全部都展示

猜你喜欢

转载自www.cnblogs.com/gongshu/p/10415046.html