mysql数据的基本查询

一、学习环境:

共三张表,分别是TScore分数表 ,TStudent学生表 ,TSubject科目表。字段如图:

****以上数据信息全为函数自动生成,身份证及名称并非真实****

二、使用select语句查询数据

4.1.1指定列

查询所有行

SELECT * FROM TStudent

使用where子句指定行

请查询:名字叫'吕宁言'的学生的姓名、性别、身份证号、邮箱?

SELECT Sname,sex,cardID,Birthday,Email FROM TStudent WHERE Sname='吕宁言'

4.1.2过滤数据

使用比较操作符 = > < >= <= <>

请查询:查询分数小于60的学生ID?

select * from TScore select * from TScore where mark<=60

4.1.3 使用逻辑操作符

AND和OR的使用

SELECT * FROM TStudent WHERE Sname='曹园贞' AND Class='测试' AND sex='女' SELECT * FROM TStudent WHERE Sname='曹园贞' OR Sname='邓咏桂'

like的使用:

查询以‘高’姓学生的信息?

select * from TStudent where sname like '高%' select * from TStudent where sname like '高%' 
select * from TStudent where sname like '高%' select * from TStudent where sname not like '高%' #反向

查询姓名中有‘月’字的学生的信息?

select * from TStudent where sname like '%月%' select * from TStudent where sname like '%月%' 
select * from TStudent where sname like '%月%' select * from TStudent where sname not like '%月%' 反向

4.1.4 查询在一定范围内的值

between的使用:

select * from TScore where mark between 70 and 80 
等价于 
select * from TScore where mark>=70 and mark<=80

包含两头,包含70和80

4.1.5 使用值的列表作为搜索条件

in的使用:

select * from TStudent where Class in ('开发','网络')
等价于
select * from TStudent where Class='开发' or Class='网络'

4.1.6 查询未知的值 空值

查找班级为空的学生
select * from TStudent where Class is null
查找班级不为空的学生
select * from TStudent where Class is not null

4.2 格式化结果集

ORDER BY 语句用于对结果集进行排序。

select StudentID,subJectID,mark from dbo.TScore order by 2,3 desc
select StudentID,subJectID,mark from dbo.TScore order by subJectID,mark desc

asc 升序,desc 降序

4.2.1 消除重复的行

distinct的使用

select distinct Class from TStudent

4.2.2 改变字段的名字

-- 给查询结果的列名称进行重命名:

SELECT
	StudentID AS '学号',
	Sname AS '姓名',
	sex AS '性别',
	cardID AS '身份证号',
	Birthday AS '生日',
	Email AS '邮件',
	Class AS '专业',
	enterTime AS '录入时间' 
FROM
	Tstudent

等价于

SELECT
	StudentID '学号',
	Sname '姓名',
	sex '性别',
	cardID '身份证号',
	Birthday '生日',
	Email '邮件',
	Class '专业',
	enterTime '录入时间' 
FROM
	TStudent

4.2.5 计算列

年龄是计算列

SELECT StudentID AS '学号', Sname AS '姓名', sex AS '性别', cardID AS '身份证号', Birthday AS '生日', Email AS '邮件', Class AS '专业', enterTime AS '录入时间', Datediff( yy, Birthday, getdate ( ) ) AS '年龄' FROM TStudent

这个有问题!还没有研究出来

发布了44 篇原创文章 · 获赞 6 · 访问量 6347

猜你喜欢

转载自blog.csdn.net/annita2019/article/details/103613421