Personal summary about mysq

During this period of time, the assigned task is to test the homepage data of the operation background, and count some data information in certain time periods.

Ready to work:

1. Get the current time:

select now()

Results: 2019-10-12 17:00:48

2. Timestamp conversion:

1. Convert the year, month, day, hour, minute, and second to a timestamp:

UNIX_TIMESTAMP(NOW())

2. Convert the timestamp to year, month, day, hour, minute and second:

FROM_UNIXTIME(时间戳) 
例如:FROM_UNIXTIME(1539238971)

3. Get the time before the current time, the previous few months, and the previous year

1. n days before

DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL n DAY), '%Y-%m-%d 00:00:00')
等价于
DATE_SUB(CURDATE(), INTERVAL n DAY) 默认的时间格式就是 %Y-%m-%d 00:00:00 下面类似

2. The first n weeks:

DATE_SUB(CURDATE(), INTERVAL n WEEK)

3. The first n months

DATE_SUB(CURDATE(), INTERVAL n MONTH)

4. The first n years

DATE_SUB(CURDATE(), INTERVAL n YEAR)

In summary: DATE_SUB (date, time interval, time interval type) can be flexibly replaced as follows:

1111

4. Statistics on a daily basis

SELECT FROM_UNIXTIME(create_time,'%Y-%m-%d') as time , count(*) as count FROM 表名 where 条件 GROUP BY  time

因为我的时间是linux时间戳,所以FROM_UNIXTIME()去转换

Attach my test code:

select DATE_FORMAT(FROM_UNIXTIME(soc.pay_time), '%Y-%m-%d') Day,count(*),sum(soc.paid_money)from so_order as so 
left join so_order_charge as soc on  so.charge_id = soc.id where so.status != 0 and so.order_type in (0, 1, 2, 3, 6) and so.shop_id != 0 
and soc.pay_time between UNIX_TIMESTAMP(DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 7 DAY), '%Y-%m-%d 00:00:00')) and UNIX_TIMESTAMP(DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 00:00:00')) 
GROUP BY Day ORDER BY so.create_time desc

 

Guess you like

Origin blog.csdn.net/qq_25162431/article/details/102523958