一、sql语句执行顺序
- from
- join
- on
- where
- group by
- avg,sum,count等各种函数
- having
- select
- distinct
- order by(asc(升序),desc(降序))
- LIMIT
二、如何获取表记录,或者某字段不同值个数
select
count(distinct a.user_id) as cnt
from table a
三、如何在sql表(假设为表a)中删除重复行
方法1:
stp1:筛选出不重复的表记录
select distinct a.* from a
stp2:将记录插入到临时表b中
insert into b
select distinct a.* from a
stp3:清空表a
truncate table a
stp4:将临时表数据插入表a
insert into a
select * from b
方法2:
delete from a
where (a.col_1,a.col_2) in
( select col_1,col_2
from a
group by col_1,col_2
having count(*) > 1)
and rowid not in (select min(rowid) a vitae group by col_1,col_2 having count(*)>1)
四、My Sql row_number...partition_by函数以及如何模拟它
SELECT collect_user_name, collect_time,rank
FROM
(
SELECT t.collect_user_name,t.collect_time,
CASE WHEN @partition_by =null or @partition_by!= t.collect_user_name THEN @rownum := 1
ELSE @rownum :=@rownum + 1
END AS rank
,@partition_by := t.collect_user_name AS partition_by
FROM (select @partition_by:=null, @rownum:=0)s, (
SELECT collect_user_name, collect_time FROM pl_collect_call_info cat
WHERE date(cat.collect_time) = curdate()
ORDER BY cat.collect_user_name,cat.collect_time
) t
#INNER JOIN (SELECT @rownum :=0) r ON 1=1
#INNER JOIN (SELECT @partition_by :='') p ON 1=1
#ORDER BY t.collect_user_name, t.collect_time
)tb ;
五、My SQL间隔进行日期和时间算术,以及示例
日期间比较:date(regist_time)>=curdate() - interval 2 day
日期间计算:datediff(a,b):返回a,b相隔天数; adddate(a,n):a加上n天;subdate(a,n):a减去n天;
返回当前时间:curtime(),current_time();
返回当前日期和时间:now(), current_timestamp(), localtime(), localtimestamp(), sysdate()
日期和时间格式
年月日:DATE_FORMAT(cld.calendar_date, '%Y%m%d')
时分秒:DATE_FORMAT(NOW(),'%H:%i:%s'), H :24小时格式;h:12小时格式。
年月日&时分秒:DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s')
时间差函数:
datediff函数,返回值是相差的天数,不能定位到小时、分钟和秒。
-- 相差2天(a-b)
select datediff('2018-03-22 09:00:00', '2018-03-20 07:00:00');
TIMEDIFF函数,按时间格式返回时间差,含时分秒。语法:timediff(time1,time2):返回两个时间相减得到的差值,time1-time2
SELECT timediff('2018-05-21 14:51:43','2018-05-19 12:54:43');
TIMESTAMPDIFF函数,有参数设置,可以具体精确到天(DAY)、小时(HOUR),分钟(MINUTE)和秒(SECOND),使用起来比datediff函数更加灵活。对于比较的两个时间,时间小的放在前面,时间大的放在后面。
--相差1天
select TIMESTAMPDIFF(DAY, '2018-03-20 23:59:00', '2015-03-22 00:00:00');
--相差49小时
select TIMESTAMPDIFF(HOUR, '2018-03-20 09:00:00', '2018-03-22 10:00:00');
--相差2940分钟
select TIMESTAMPDIFF(MINUTE, '2018-03-20 09:00:00', '2018-03-22 10:00:00');
--相差176400秒
select TIMESTAMPDIFF(SECOND, '2018-03-20 09:00:00', '2018-03-22 10:00:00');
六、