SQL server常用操作
查询: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(id) as totalcount from table1
求和:select sum(id) as sumvalue from table1
平均:select avg(id) as avgvalue from table1
最大:select max(id) as maxvalue from table1
最小:select min(id) as minvalue from table1
链接查询
1、inner join 内连接查询
select * from student a inner join course b on a.id=b.id
2、left (outer) join: 左链接查询
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
SQL: select * from student a left join course b on a.id=b.id
3:right (outer) join: 右链接查询
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
SQL: select * from student a right join course b on a.id=b.id
4:full/cross (outer) join: 完全链接查询
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
SQL: select * from student a full join course b on a.id=b.id
子查询和内嵌查询
1、子查询
select * from student where id in (select id from course)
或 select * from student where id in (1,2,3)
2、带 in 的嵌套查询 not in与in查询相反
select * from student where id in (1,2,3) 查询id为1,2,3的数值
3、some 和any 和 all 查询
select * from student where idd >(select id from course ) 如果不加any 数据库是不执行的 正确的select * from student where idd >any(select id from course )
some 和any 是等效的,all要求where的查询表达式与子查询返回的每个值进行比较时都应满足条件,some和any则要求where的表达式与子查询返回的值进行比较时至少有一个满足条件
some : select * from student where idd >some(select id from course )
any : select * from student where idd >any(select id from course )
all : select * from student where idd >any(select id from course )
4、使用case函数进行查询
select *,
case
when idd>=5 then '优秀'
when idd>=10 and idd<=6 then '中等'
else '不及格'
end
from student
模糊查询与范围查询
1 、between and 查询
select * from student where idd between 3 and 4 查询3和4之间的数据,包括3和4。
2、% 查询
select * from student where name like '%程%' 查询名字中包含‘程’ 的数值
3、_ 查询
select * from student where name like '程_' 查询名字中开头包含‘程’ 的数值
select * from student where name like '_g' 查询名字中结尾包含‘g’ 的数值
4、[] 查询
select * from student where name like '[mr]%' 查询以mr开头的数值
select * from student where name like '[^mr]%' 查询不是以mr开头的数值