函数
函数分类:注意mysql是忽视大小写的
时间类的函数
now()=current_timestamp=current_timestamp() curdate()=current_date=current_date()
dayName(date)指定时间的名称 例如星期三, 类似函数monthname
weekofyear(curdate())本周是今年的第几周, 类似的函数dayofyear(date)1-365
quarter(date)本季度是今年的第几季度
hour(time),second(time),minute(time)指定时间的时分秒
extract(unit from date)抽取指定时间的时间单位,unit包括SECOND ,MINUTE,HOUR,DAY,WEEK,MONTH,QUARTER,YEAR等
查询某一段时间的数据
查询今天的数据
select * from table where to_days(column_time_field)=to_days(now())
查询昨天的数据
select * from table where to_days(column_time_field)-to_days(now())<=1
查询近7天的数据
select * from table where date_sub(now(),internal 7 DAY)<=date(CURDATE())
查询本周的数据
select * from table where YEARWEEK(date_format(column_time_field,"%Y-%m-%d"))=YEARWEEK(now())
查询本月的数据
select * from table where date_format(column_time_field,"%Y%m")=date_format(CURDATE(),"%Y%m")
.查询上一个月的数据
select * from table where period_diff(date_format(now(),"%Y%m"),date_format(column_time_field,"%Y%m"))=1
查询本季度的数据
select * from table where QUARIER(column_time_field)=QUARIER(now())
查询上个季度的数据
select * from table where QUARIER(column_time_field)=QUARIER(date_sub(now()) , internal 1 QUARIER)
查询本年度的数据
select * from table where YEAR(column_time_field)=YEAR(now())
查询上个年度的数据
select * from table where YEAR(column_time_field)=YEAR(DATA_SUB(now(), internal 1 YEAR))
关键字
on duplicate key update
此语句语法如下:
INSERT INTO tablename(field1,field2, field3, ...)
VALUES(value1, value2, value3, ...)
ON DUPLICATEKEY UPDATE field1=value1,field2=value2, field3=value3, ...;
当我们数据库表中含有unique key或者primary key,并且我们往往会在 数据库中插入一条已有相同key的数据的时候,此时使用on duplicate key update语句,就会产生如下效果:
如果数据库表中没有此相同key的数据,就会插入,如果有则更新某些字段的数据。
insert ignore
insert ignore into表示:会忽略数据库中已经存在 的数据,如果数据库没有数据,就插入新的数据,如果有数据的话就跳过当前插入的这条数据。这样就可以保留数据库中已经存在数据,达到在间隙中插入数据的目的。
replace和replace into
replace into的语法如下:
insert into test(title,uid) VALUES ('123465','1001');
REPLACE INTO test(title,uid) VALUES ('1234657','1003');
用法基本上和insert into相同,当有unique key或者primary key的重复旧数据,replace into会删除旧数据,再插入新数据,如果没有则直接插入新数据,注意replace into必须使用在含有primary key或者unique key的表中,并且影响2行
--新建一个test表,三个字段,id,title,uid, id是自增的主键,uid是唯一索引;
insert into test(title,uid) VALUES ('123465','1001');
insert into test(title,uid) VALUES ('123465','1002');
--执行单条插入数据可以看到,执行结果如下:
[SQL]insert into test(title,uid) VALUES ('123465','1001');
受影响的行: 1
时间: 0.175s
--使用 replace into插入数据时:
REPLACE INTO test(title,uid) VALUES ('1234657','1003');
执行结果:
[SQL]REPLACE INTO test(title,uid) VALUES ('1234657','1003');
受影响的行: 1
时间: 0.035s
--当有重复key旧数据存在,使用replace into 语句
REPLACE INTO test(title,uid) VALUES ('1234657','1001');
[SQL]REPLACE INTO test(title,uid) VALUES ('1234657','1001');
受影响的行: 2
时间: 0.140s
set case when then条件选择语句
如果需要针对某个字段的值针对不同条件设置不同值的时候,使用set 语法,该语法例子如下:
update table_name
set column_name=(
case
when condition1 then value1
when condition2 then value2
end
);