SQL server基础复习

112 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情 >>

前言

在之前工作中都是使用mysql数据库,使用navicat连接数据库,可视化创建表、查询等等,在程序中就写增删改查的语句,导致创建表、清空表这些语句都不熟悉了,只会鼠标创建什么的。现在新工作使用了sqlserver数据库。并且大家都更多的直接写sql语句。所以今天就复习一下sql语句相关的。计划明天更新sql的触发器、游标的。话不多说我们马上开始。

SQL server管理套件

日常大家都使用的是SSMS(SQL Server 2014 Management Studio)我更喜欢使用开源的DBeaver,也很推荐这个数据库连接工具。这块不多介绍了。

操作数据库

  • 创建:CREATE DATABASE database-name
  • 删除:drop database dbname

操作表

  • 新建表:create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
  • 根据已有表创建新表
A:create table tab_new like tab_old (使用旧表创建新表)\
B:create table tab_new as select col1,col2… from tab_old definition only
  • 删除表 :drop table tabname
  • 添加主键:Alter table tabname add primary key(col)
  • 删除主键:Alter table tabname drop primary key(col)

操作数据

选择: 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%’
排序: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

连接查询

  • 左连接: 即左外连接。执行规则:返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值。
select Student.sid, Student.sname, Score.score from Student left join Score on Student.sid = Score.sid
  • 右连接:即右外连接。执行规则:与左连接相反,返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。
select Student.sid, Student.sname, Score.score from Student right join Score on Student.sid = Score.sid
  • 内连接 获取两个表中公共的部分。