数据查询基础
复习:
--查询:select * from 表名
--添加:insert [into] 表名(列名)values(值)
Default关键字
第一种:通过insert select 语句添加(将现有表中的数据添加到已存在的表中)
Insert into <表名>(列名)
Select <列值>
From<源表名>
第二种:通过select into语句添加(将现有表中的数据添加到新表:不创建新表)
Select(列名)
Into <新表名>
From <源表名>
第三种:通过Union关键字来多行插入数据
Insert into<表名>(列名)
Select <列的值>union
……………
Select <列的值>
--修改:update 表名 set 列名 = 更新值 where 更新条件
--删除:delete from 表名 where 条件
使用select语句进行查询
语法:select <列名/* >
From <表名>
Where <查询条件表达式>
[Order by<排序的列名>[asc或desc]]
查全部的行和列
-- 查询所有学生信息
select * from Students--ScoreCourse
--查询学生的姓名和地址
select SName,SAddress from Students
--查询“北京”的学生
select SName,SAddress from Students where SAddress = '北京海淀'
--select * from Students where SAddress like '%北京%'
select SName,SAddress,SEmail from Students where SSex = 1
查部分列
-- 查部分列
select SCode,SName,SAddress from Students where SAddress = '四川成都'
select SCode,SName,SAddress from Students where SAddress <> '四川成都'
列别名
AS关键字
--列的别名
select SName as 学生姓名,SAddress AS 家庭住址 from Students
--列的别名
select SName as 学生姓名,SAddress AS 家庭住址 from Students where SAddress <> '上海松江'
使用“=”命名列
select SName +'~'+ SName AS 姓名 from Students
select 姓名 = SName +'~'+ SName from Students
查询空行
select * from Students where SEmail is null
select * from Students where SEmail = ''
--查询常量值
select *,'清华大学' as School from Students where SGrade = 1
select *,'北京大学' as School from Students where SGrade = 2
--限制行数(限制固定行数)
select top 2 * from Students [where SName = '']
--按百分比返回行
select top 50 percent * from Students [where SName = '']
查询单列排序
--Order by 升序
select StudentID,Score from Score Order by Score
select StudentID as 学生编号,(Score * 0.9 + 5) as 综合成绩
from Score
where (Score* 0.9 + 5) > 60
Order by Score
--降序排序
select StudentID,Score from Score Order by Score DESC
--查询多列排序
select StudentID as 学生编号,CourseID as 课程编号,Score as 成绩
from Score
where Score > 60
Order by CourseID,Score
小结
select * from Student where Address LIKE '%河北%' and Sex = '男'
--连表查询
-- Result连接Student表,通过Result表中的StudentNo连接Student表中的StudentNo
查询成绩表中的前5条数据,并显示姓名和成绩这两列,成绩按照降序排列
select top 5 StudentName,StudentResult from Result inner join Student a
on Result.StudentNo = a.StudentNo
Order by StudentResult DESC