1.isnull
给空值设定新值。
如:
select isnull(Fname,'佚名') as 姓名
from T_Employee;
Fname为列名,如果Fname不为空值,则显示原本的值,为空值则改为’佚名’。
所以总结: isnull(expression,value):如果列名不为空则返回列名,否则返回value。
2.case函数,重点
先给出单指判断的模板:
case expression
when value1 then returnvalue1
when value2 then returnvalue2
when value3 then returnvalue3
....
else defalutreturnvalue --默认返回值
end
给出一个表:
select FName,(case Flevel
when 1 then 'VIP客户'
when 2 then '高级客户'
when 3 then '普通客户'
else '客户类型错误'
end)
as FlevelName
from T_Customer;
会输出:
也可以用范围来替换值
select FName,(case
when FSalary < 2000 then '低收入'
when FSalary >= 2000 and FSalary <= 5000 then '中等收入'
else '高收入'
end) as 收入水平
from T_Employee
所以。在用范围来替换值时,case一行后不加要查询的列名。
3.查询空值
MySQL中查询空值:
1.select * from table where 列名 = ''
–适用于没有值时使用
2.select * from table where 列名 is null
–适用于查询默认空值
3.select * from table where 列名 = 'NULL'
–适用于列中填的就是NULL
4.join
left join 和 right join:
以左(右)表为准,右(左)表数据匹配,有匹配数据则获取数据,如果左(右)表有的数据右(左)表没有,则以NULL填充,如果右(左)表有的数据左(右)表没有,则过滤数据。
inner join
只会返回两个表都有部分,否则过滤
5.注意事项
进行delete,update,drop操作前一定要注意先备份表,避免操作失误而无法恢复
6.一些常用函数
abs()
:求绝对值
ceiling()
:舍入到最大整数 3.33 —> 4 -3.61 —> -3
floor()
:舍入到最小整数 3.33 —> 3 -.361 —> -4
round()
:四舍五入
round(value,num)
:保留几位小数 如:round(3.1415926,2)
—> 3.14
len()
:计算字符串长度
lower()
, upper()
:将传入的值或列转为小写,大写
getdate()
:返回当前日期时间
dateadd(datepart,number,date)
:计算增加值后的日期。
datepart为计量单位,如Month,year,day
number为增加或减少的数量
date为要计算的基础时间
如:
dateadd(month,-8,date)
datediff(datepart,startdate,enddate)
:计算两个日期之间的差额。
datepart(datepart,date)
:返回一个日期的特定部分(年,月….)
如用datediff和getdate来计算员工的工龄。
select FName,FInDate,datediff(year,FInDate,getdate())
from T_Empolyee
7.类型转换函数
cast(expression as data_type)
convert(data_type,expreession)
举例说明:
select cast('123' as int),cast('2008-08-08' as datetime),
convert(datetime,'2009-09-09'),convert(varchar(50),123)
合理运用类型转换函数,作用就是避免出现数据类型不符合我们计算的情况。
比如:
select datepart(year,cast('2008-08-08' as datetime))
select convert(int,'123') + 1
8.Union
union用来合并两个查询结果集,并且将其中完全重复的数据合并为一条。
另:union因为要进行重复值扫描,所以效率低,因此如果不是确定要合并重复行,那么就用union all。
举个例子:
select FNumber,FSalary
from T_Employee
union
select '工资合计',sum(FSalary)
from T_Employee
select '正式员工最高年龄',max(FAge)
from T_Employee
union all
select '正式员工最低年龄',min(FAge)
from T_Employee
union all
select '临时工最高年龄',max(FAge)
from T_TempEmployee
union all
select '临时工最低年龄',min(FAge)
from T_TempEmployee
这样能够有效避免出现年龄一样而合并的情况。
9.MySQL中的拼接操作补充
在基础篇说过Sql Server中的拼接操作。
select 列名 + ' ( ' + 列名 + ' ) '
在MySQL中的拼接操作则需要用到concat函数
select concat (vend_name,'(',列名,')')
from 表名
order by vend_name;
则会输出
vend_name(列名)
vend_name(列名)
……
当然拼接操作则少不了去掉空格的操作。
select concat(rtrim(vend_name),'(',rtrim(列名),')')
10.not in 与 in 的区别
not in不会自动忽略空值,in会忽略空值。
如果后面的数据集里面有空值,则输出结果为空集,所以我们需要剔除null。
则可以在子查询中加上where 列名 is not null。
select *
from 表名
where 列名 not in (select 列名
from 表名
where 列名 is not null);
到这儿SQL语言的大部分操作就差不多更完了。后面再开始慢慢更统计学和python吧,争取每天写几点(●’◡’●)