mysql查询本月数据sql怎么写

mysql查询本月数据sql怎么写,第1张

首先要考虑给数据库减压,意思就是让数据库做最简单的事情。你可以把条件在php里边组装好,然后让mysql只单一的执行查询就好了,php的时间代码给你贴一下吧

'

//php获取今日开始时间戳和结束时间戳?

$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'))

$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1

echo?"今日开始时间戳和结束时间戳",'开始:',$beginToday,'结束:',$endToday,'

'

echo?"今日开始时间:",date("Y-m-d?H:i:s",$beginToday),'

'

echo?"今日结束时间:",date("Y-m-d?H:i:s",$endToday),'

'

echo?''

//php获取昨日起始时间戳和结束时间戳

$beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'))

$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1?

echo?"昨日开始时间戳和结束时间戳",'开始:',$beginYesterday,'结束:',$endYesterday,'

'

echo?"昨日开始时间:",date("Y-m-d?H:i:s",$beginYesterday),'

'

echo?"昨日结束时间:",date("Y-m-d?H:i:s",$endYesterday),'

'

echo?''

//php获取上周起始时间戳和结束时间戳

$beginLastweek=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))

$endLastweek=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))

echo?"上周开始时间戳和结束时间戳",'开始:',$beginLastweek,'结束:',$endLastweek,'

'

echo?"上周开始时间:",date("Y-m-d?H:i:s",$beginLastweek),'

'

echo?"上周结束时间:",date("Y-m-d?H:i:s",$endLastweek),'

'

echo?''

//php获取本月起始时间戳和结束时间戳

$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'))

$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'))

echo?"本月开始时间戳和结束时间戳",'开始:',$beginThismonth,'结束:',$endThismonth,'

'

echo?"本月开始时间:",date("Y-m-d?H:i:s",$beginThismonth),'

'

echo?"本月结束时间:",date("Y-m-d?H:i:s",$endThismonth),'

'

?>

select

*

from

shipmentlist,shipmentscrib

where

(shipmentlist.shipmentlistno=shipmentscrib.shipmentlistno)

and (year(shipmentlist.shipmentdate)=year(now()))

and (month(shipmentlist.shipmentdate)=month(now())

or month(shipmentlist.shipmentdate)=month(now())-1 )

ORDER BY shipmentdate DESC

格式化了一下你的SQL,分析一下。

假如今天是 2012年1月1日。

那么上面的条件。

将变为

year = 2012 and month = 1 OR month = 0

其实,对于 查询 当月和上一月

相当于

shipmentlist.shipmentdate >= 上月的1号

AND shipmentlist.shipmentdate <下月的1号

LAST_DAY(NOW()) 可以获取 本月的最后一天.

DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) 可以获取下月第一天。

DATE_SUB ( DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) INTERVAL 2 MONTH ) 可以获取上月的1号

(也就是用 下月的1号 减少2个月,从而获取 上月的1号)

最后 SQL 修改为:

select

*

from

shipmentlist,shipmentscrib

where

(shipmentlist.shipmentlistno=shipmentscrib.shipmentlistno)

and shipmentlist.shipmentdate >= DATE_SUB ( DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY ) INTERVAL 2 MONTH )

AND shipmentlist.shipmentdate <DATE_ADD( LAST_DAY(NOW()) INTERVAL 1 DAY )

ORDER BY shipmentdate DESC

mysql 怎么获取前一个月的日期和前一年的日期

set @dt = now()

select extract(year_month from date_add(@dt, interval -1 month))

select extract(year_month from date_add(@dt, interval -1 year))

这样就可以了


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/8636597.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存