常用的SQL命令

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

基础

登录数据库

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

创建数据库

  1. create database database-name;

删除数据库

  1. drop database database-name;

进入数据库

  1. use databse-name;

创建新表

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

删除表

  1. drop table table-name;

新增列

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

添加主键

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

删除主键

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

创建索引

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

删除索引

  1. drop index index-name;

基本的sql语句

  1. 选择:select * from table1 where 范围
  2. 插入:insert into table1(field1,field2) values(value1,value2)
  3. 删除:delete from table1 where 范围
  4. 更新:update table1 set field1=value1 where 范围
  5. 查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
  6. 排序:select * from table1 order by field1,field2 [desc]
  7. 总数:select count as totalcount from table1
  8. 求和:select sum(field1) as sumvalue from table1
  9. 平均:select avg(field1) as avgvalue from table1
  10. 最大:select max(field1) as maxvalue from table1
  11. 最小:select min(field1) as minvalue from table1

高级的查询运算符

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

外连接

  1. 左外连接(左连接):结果集包括连接表的匹配行,也包括左连接表的所有行。
  2. //select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUTER JOIN b ON a.a = b.c
  3. 右外连接(右连接):结果集包括连接表的匹配行,也包括左连接表的所有行。
  4. //select a.a, a.b, a.c, b.c, b.d, b.f from a RIGHT OUTER JOIN b ON a.a = b.c
  5. 全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
  6. //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

相关文章