语法:IF(condition,result,result)
如果函数的第一个参数中给定的condition符合条件(如,condition不等于0或者不为NULL),那么函数的执行结果为第二个参数中给定的result值,反之,如果第一个参数中的condition值确实等于0或者为NULL,该函数将返回第三个参数中给定的result值,注意,condition的值被替换成了整数值,因此,当试图匹配字符串或者浮点值时,请事情比较运算符。
示例:有一张用户表,里面有3个字段,分别是uuid,mobile,age,如何用SQL写出age=12,age=46,其余的age归类均默认等于9的查询语句
要求:#将此查询结果进行age的分类统计,预期结果:12是1个,46是1个,其余的age归类均默认等于9的是2个#
select uuid,mobile,count(age) as "统计", if(age=12,12, if(age=46,46,9
)
)as age0 from user where mobile="53437569" group by age0;
#注意取as后面的别名,避免取与数据库中存在字段名称相同的命名,否则会导致系统自己都不知道取哪个字段进行解析,我就犯了这个错age0之前写的是age
若需要更多年龄的计算,则依此类推:
select uuid,count(age) as "统计",
if(age=46,46,
if(age=40,40,
if(age=88,88,1)
))as age0
from user
group by age0;
注:《mysql核心技术手册》中有关这节讲解的一个示例,粘贴此处供自己后期参考
SELECT clients.client_id AS ID,
CONCAT(name_first, SPACE(1), name_last) AS Client,
telephone_home AS Telephone, SUM(qty) AS Shares,
IF(
(SELECT SUM(qty * price)
FROM investments, stock_prices
WHERE stock_symbol = symbol
AND client_id = ID )
> 100000, 'Large', 'Small') AS 'Size'
FROM clients, investments
WHERE stock_symbol = 'GT'
AND clients.client_id = investments.client_id
GROUP BY clients.client_id LIMIT 2;