Sqlserver单表查询
注意:如果 like 后面的字符串不含有通配符(%,_用于模糊查询),那么 = 等价于 like
use stuinfo
-- 单表查询
/* 查询全部学生的全部信息*/
select * from stu -- *表示查询stu表的所有内容
select * from major
select * from sc
select * from cou
/* 查询全部学生的学号sno 和 姓名sname */
select sno,sname from stu
/* 查询全部学生的姓名和出世年份 */
select sname,2021-age from stu -- 执行,可以发现年份那列显示无列名
select sname,2021-age as birth_date from stu -- as 列名 给年份那列加 birth_date 作为列名
/* 查询有选修课程的学生学号 distinct 去重 */
select distinct sno from sc
/* 查询姓名是 "小十" 的学生的全部信息 俩种方法 like或= */
select * from stu where sname='小十'
select * from stu where sname like '小十'
/* 查询课号cno是 "20201" 且学生grade成绩高于80的学生学号sno like或= */
select sno from sc where cno='20201' and grade>80 -- !=(不等于) >= <= <>(不等于)
-- 如果 like 后面的字符串不含有通配符(%,_用于模糊查询),那么 = 等价于 like
/* 查询年龄在 18-19 之间的学生姓名,年龄 2 种写法 */
-- 第一种用 and
select sname,age from stu where age>=18 and age<=19
-- 第二种 between and
select sname,age from stu where age between 18 and 19
/* 查询 专业号 01,02,04 的学生信息 2种写法 in */
-- 第一种 or
select * from stu where mno=01 or mno=02 or mno=04
-- 第二种 in
select * from stu where mno in(1,2,4)
/* 查询专业号不是01,02,04 的学生信息 2种方法 not in */
-- 第一种 not in
select * from stu where mno not in(1,2 ,4)
-- 第二种 取反
select * from stu where mno!=1 or mno!=2 or mno!=4
/* 查询所有姓 "彭" 的学生信息(模糊查询) */
select * from stu where sname like '彭%'
/* 查询名字中第二个字为 "小" 的学生信息 */
select * from stu where sname like '_小%'
/* 查询名字有 "小" 的学生信息 */
select * from stu where sname like '%小%'
/* 查询有选课记录,没有考试成绩的选课信息 */
select * from sc where grade is null