数据查询基础
一、查询基础
1.数据库存储数据的目的就是为了查询
2.查询是最能体现数据库魅力的一个方面
3.查询的本质就是数据的筛选
4.select:选择,查找
5.select语句用于查询,语法如下
select 列名 from 表名 [where 条件] [order by 排序列 [asc / desc] ]
6.查询所有行和所有列
select * from Student
7.查询部分列
select stuName,stuAge from Student
8.给列起别名
select stuName as 姓名 stuAge as 年龄 from Student
select stuName name ,stuAge age from Student --as 可以省略
select stuName 'name' from Student --可以带单引号,防止特殊符号或空格
9.通过where条件查询部分行
select * from student where stuSex='男'
10.多条件查询
select * from student where stuSex='男' and stuAge > 22
二、查询基础
1.查询空值
select * from BookInfo where bookAuthor is null
2.在查询中使用常量列
select stuName,stuAge,'中心小学' as schoolName from Student
3.列和列之间可以计算或者连接,产生新列
select bookPrice * bookCount as totalMoney from BookInfo
select bookDesc=bookName + '-' + bookAuthor from BookInfo
4.返回限制的行数
a、select top 5 * from Student --返回前5条
b、select top 20 perent * from Student --返回前百分之20的数据
5.排序
a、asc表示升序,desc表示降序
b、默认是asc升序
c、使用order by来指定排序列
d、多个排序列之间,逗号分隔
三、在查询中使用函数1
1.输出语句
a、select
b、print
2.字符串函数
charIndex("cd" , "abcdecdfg" , 4) --》 返回查找到的字符串的位置,从开始
len("abcd") --》 求字符串长度
upper()/ lower() --》 转大写、转小写
ltrim()/ rtrim() --》 去除左边、右边的空格
right("abcdef",3) --》 从右向左截取指定长度的字符串
replace("abcdef","ab","xx") --》 替换字符串
stuff("abcdef ",2,3,"xxx") --》 从指定位置删除指定长度字符串,再插入内容
3.数学函数
rand() --》 生成0-1之间的随机float值
abs(-43) --》 求绝对值
ceiling(43.5) --》 向上取整
floor(43.5) --》 向下取整
power(5,2) --》 取幂值
round(43.543,2) --》 将数值表达式四舍五入为指定精度
sign(-1) --》 对于整数返回+1,负数返回-1,0返回0, 判断数字是正数还是负数
sqrt(9) --》 求平方根
四、在查询中使用函数2
1.日期函数
getDate() --》 获得系统当前时间
dateAdd(mm,4,"1990-05-06") --》 给日期的指定部分添加指定值
dateDiff(mm,"1990-05-01","1991-05-01") --》 求两个日期的差
dateName(dw,"1990-01-02") --》 日期中指定日期部分的字符串形式
datePart(year,"1990-01-02") --》 日期中指定日期部分的整数形式
2.日期部分参数及其缩写
year(yy,yyyy) weckday(dw,w) hour(hh)
quart(qq,q) month(mm,m) minute(mi,n)
dayofyear(dy,y) second(ss,s) day(dd,d)
millisecond(ms) week(wk,ww) day(dd,d)
3.系统函数
convert(varchar(10),12345) --》 数据类型转换
current_user --》 返回当前用户名
dataLength("我s") --》 返回表达式占用的字节数
host_name() --》 返回当前计算机名
system_user --》 返回当前登录名