常用的SQL命令

x33g5p2x  于2022-02-12 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(154)

基础

登录数据库

mysql -u root -p;
输入数据库密码;

创建数据库

create database database-name;

删除数据库

drop database database-name;

进入数据库

use databse-name;

创建新表

create table table-name(col1 type1 [not null] [primary key],col2 type2 [not null],..);
//根据已有表创建新表
create table tab-new like tab-old;

删除表

drop table table-name;

新增列

alter table table-anme add column col-name type;
//列增加后将不能删除。列加上后数据类型也不能改变,唯一能改变的是增加varchar类型

添加主键

alter table table-name add primary key(column-name);

删除主键

alter table table-name drop primary key(column-name);

创建索引

create [unique] index index-name on table-name(col,...);
//[]中为可选,索引的类型有:fulltext,unique,normal,spatial

删除索引

drop index index-name;

基本的sql语句

选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数: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

高级的查询运算符

union:返回两个结果集的并集
except:返回两个结果集(即从左查询中返回没有找到的所有非重复值)。
intersect:返回两个结果集的交集(即两个查询都返回的所有非重复值)。
*注:使用运算符的几个查询结果行必须是一致的。如果想保留重复行,在命令后加上all,

外连接

左外连接(左连接):结果集包括连接表的匹配行,也包括左连接表的所有行。
//select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUTER JOIN b ON a.a = b.c
右外连接(右连接):结果集包括连接表的匹配行,也包括左连接表的所有行。
//select a.a, a.b, a.c, b.c, b.d, b.f from a RIGHT OUTER JOIN b ON a.a = b.c
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
//select a.a, a.b, a.c, b.c, b.d, b.f from a FULL OUTER JOIN b ON a.a = b.c

未完,持续学习更新ing

相关文章