时间格式转换:
DATE_FORMAT(字段名,'%Y-%m-%d %h-%i-%s') 新字段名
eg:
统计2025年内的总数,可用函数提取年份
year(date)='2025',date_format(date,'%Y')='2025'
CAST(TIMESTAMPDIFF(SECOND,字段1,字段2)/3600.00 AS DECIMAL(9,2)) AS 新字段名
DAY(字段名) = DAY(NOW())
排序:
rank() over(order by id desc) as t
dense_rank() over(order by id desc) as t
row_number() over(order by id desc) as t
中英文排序:
convert(待排序的字段名 using gbk) ASC
区别如图:
sum(if(type='add',grade_num,-1*grade_num)) as grade
使用 ROUND(聚合函数,精确到小数点后几位)
round(avg(score),3) as avg
本题用ceiling函数向上取整(返回不小于该数的最小整数值)
case when count(score)%2=0 then ceiling(count(score)/2) else ceiling(count(score)/2) end as start1 ,
case when count(score)%2=0 then ceiling(count(score)/2+1) else ceiling(count(score)/2) end as end1
sum(case email.type when'completed' then 0 else 1 end)*1.0/count(email.type),3
1)修改表数据:
update 表名 set 字段名 = 值1
2)修改表名:
alter table 表名 rename to 新表名
3)在audit表上创建外键约束,其emp_no对应employees_test表的主键id:
ALTER TABLE audit ADD FOREIGN KEY (emp_no) REFERENCES employees_test (id)
4)对first_name创建唯一索引uniq_idx_firstname,对last_name创建普通索引idx_lastname:
CREATE UNIQUE INDEX uniq_idx_firstname ON 表名(first_name);
CREATE INDEX idx_lastname ON 表名(last_name);
5)针对actor表创建视图actor_name_view,只包含first_name以及last_name两列,并对这两列重新命名,first_name为first_name_v,last_name修改为last_name_v:
CREATE VIEW actor_name_view (first_name_v, last_name_v) AS
SELECT first_name, last_name FROM actor
6)给表添加新列:
ALTER TABLE 表名 ADD COLUMN 字段名 数据类型(datetime) 是否为空(NOT NULL) DEFAULT(默认值: '2020-10-01 00:00:00')
替换replace()
REPLACE ( string_expression , string_pattern , string_replacement )
string_expression 要搜索的字符串表达式。
string_pattern 是要查找的子字符串。
string_replacement 替换字符串。
eg:
1)将emp_no=10001的数据改为10005
replace(emp_no,10001,10005)
2)把串 "10,A,B" 中的 逗号用空串替代, 变成了 "10AB"
然后原来串的长度 - 替换之后的串的长度 就是 被替换的 逗号的个数
(length("10,A,B") - length(replace("10,A,B",",","")) )
拼接字符串 concat()
CONCAT(字段1,"-",字段2)
多行作为一行展示 GROUP_CONCAT(),默认分隔符','
eg:
GROUP_CONCAT(DISTINCT 字段名)
排序: GROUP_CONCAT(字段名 ORDER BY 字段名 DESC)
分隔符: GROUP_CONCAT(字段名 SEPARATOR ';')
RIGHT(s,n)返回字符串 s 的后 n 个字符
eg:查询按照first_name最后两个字母,按照升序进行排列:
order by right(first_name,2)