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開頭的數值