MSSQL 查詢
select * from class;查詢表class中的所有列.
select * from class; 查詢表class中的所有列.
select class,teacher from class;查詢表class中的列class,teacher
Select count(*) as count_all from class;返回表class中的總行數給結果集.
select sum(studentnumber) as all_student_number from class :返回class表中studentnumber的總數給結果集
select avg(studentnumber) as avg_student_number from class :返回class中studentnumber的平均值給結果集
Select max(studentnumber) as max_studentnumber from class :求某個字段的最大值,最小值.min是最小值.
select * from class where studentnumber=(Select max(studentnumber) from class):求的最大值可以作爲條件被引用.
Select * from class where studentnumber=50(>50,>=50,<50,<=50,<>50):返回studentnumber=50 (>50,>=50,<50,<=50,不等於50):的記錄
Select * from class where studentnumber<>50 and teacher='li‘ 兩個查詢條件用and表示與,or表示或.
Select * from class where studentnumber in (44,55) : in表示studentnumber爲括號中所列的可能值.
Select * from class where class in (select class from student) :in中的內容可以是另一個查詢語句的結果.
Select distinct class from student :查詢字段的值不重複
select * from class order by studentnumber (asc,desc) :對查詢結果排序,可以按升序,也可以按降序.
續一
select class,count(*) from student group by class :查詢結果根據group by 分組.
select class,count(*) from student group by class having count(*)=5 :對分組的結果再用條件過濾
select * from student where id<2
UNION (ALL)
select * from student where age>19 :UNION:將兩個查詢語句的查詢結果放在一起,如果有重複的行,
就刪除,如果是UNION ALL:則重複的行不刪除.
模糊匹配查詢: select * from student where name like '%ang%'
整型,日期類型的字段可以指定範圍.用between
select * from student where born between '1980-05-04' and '2983-10-18'
select * ,12 from student 返回結果中增加一列,且值均爲12.
select RTRIM(class)+RTRIM(teacher) AS name1,studentnumber from class :將兩個字段先刪除尾部的空格,再連接起來返回. 其中:連接起來的字段名稱返回時爲name1
Select class.*,student.* from class,student where class.class=student.class :兩個表的內容聯合起來查詢,字段
也可以用JOIN子句實現:select * from class JOIN student on class.class=student.class
JOIN又分爲內連接,外連接,左外連接,右外連接等,具體請查看相關的數據庫的手冊.
增刪改操作
插入:
指定字段名稱及值的插入
Insert into class (class,studentnumber,teacher) values('gaoer',55,'abc');
不指定字段名稱的插入Insert into class values('chuyi','abc',55);
一次插入多條記錄:只能執行多條insert語句.
從另一個表中讀出數據插入當前的表先創建一個新表:select * into class_bak from class where 1=2
insert into class_bak select * from class where class='gaoer‘
修改:Update class set class='gaoerer' where class='gaoer‘
刪除:Delete from class where class='gaoerer'