文章目录
聚合函数
函数名(数据)
也可以 函数名(distinct 数据);
AVG()
返回组中数据中非null值的平均值;
SUM()
返回组中数据的总和
STDEV(),STDDEV_POP()
返回总体标准差
STDDEV_SAMP() 返回样本标准差
VARIANCE(),VAR_POP(),VARP_SAM()
前两个返回总体方差,后面一个返回样本方差;
比较函数
coalesce
coalesce(val1,val2,val3,...valn)
如果coalesce只有两个输入参数的话,则跟ifnull作用一样;
例子
数据:
CREATE TABLE articles (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
excerpt TEXT,
body TEXT NOT NULL,
published_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO articles(title,excerpt,body)
VALUES('MySQL COALESCE Tutorial','This tutorial is about MySQL COALESCE function', 'all about COALESCE function'),
('MySQL 8.0 New Features',null, 'The following is a list of new features in MySQL 8.0');
SELECT
id, title, excerpt, published_at
FROM
articles;
excerpt行存在null值,对body字段从左开始截取150个字符作为excerpt null值的替代;
SELECT
id, title, COALESCE(excerpt, LEFT(body, 150)), published_at
FROM
articles;
SELECT
id,
title,
(CASE
WHEN excerpt IS NULL THEN LEFT(body, 150)
ELSE excerpt
END) AS excerpt,
published_at
FROM
articles;
select coalesce(1,2,3); # 返回第一个非null值
select greatest(1,2,3); #返回最大值
select least(1,2,3); #返回最小值
select isnull(0); # is null 1 otherwise 0;
字符串函数
concat
-
语法及使用特点:
CONCAT(str1,str2,…)
返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。可以有一个或多个参数。 -
例子
select concat(last_name,' ',first_name) from Name limit 1;
select concat(last_name,' ',first_name,null) from Name limit 1;
return null;
concat_ws
CONCAT_WS(separator,str1,str2,…)
CONCAT_WS() 代表 CONCAT With Separator ,是CONCAT()的特殊形式。
select concat_ws(last_name,' ',first_name,null) from Name limit 2