如何从mysql特定月份显示数据

时间:2015-09-10 06:18:15

标签: php mysql

$query = mysql_query(
         "SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime FROM `order`
         WHERE DateTime="2015 AND 08""; LIMIT $start, $per_page"
         ) 
or die(mysql_error());

我正在尝试让查询显示特定的月份和年份。

4 个答案:

答案 0 :(得分:2)

您可以使用MySQL的内置YEARMONTH功能,例如:

SELECT `id`, `BuyerName`,`BuyerEmail`,`TransactionID`,`DateTime`   
FROM `order` WHERE YEAR(DATE(`DateTime`))=2015 AND MONTH(DATE(`DateTime`)) = 8

答案 1 :(得分:0)

如果您的列的数据类型为date,则可以Sargable方式为您的条件使用一系列日期

SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime
 FROM `order` 
WHERE DateTime >='01-08-2015' 
AND  DateTime <= '31-08-2015'

对于datetime,您可以将其写为

SELECT id, BuyerName,BuyerEmail,TransactionID,DateTime
 FROM `order` 
WHERE DateTime >='01-08-2015 00:00:00' 
AND  DateTime <= '31-08-2015 23:59:59'

答案 2 :(得分:0)

如果列的类型是datetime,那么试试这个

$query = mysql_query("
    SELECT id, BuyerName, BuyerEmail, TransactionID, `DateTime` 
    FROM `order` 
    WHERE YEAR(DATE(`DateTime`)) = 2015 AND MONTH(DATE(`DateTime`)) = 8
    LIMIT $start, $per_page
") or die(mysql_error());

或只是

$query = mysql_query("
    SELECT id, BuyerName, BuyerEmail, TransactionID, `DateTime` 
    FROM `order` 
    WHERE `DateTime` LIKE '2015-08-%'
    LIMIT $start, $per_page
") or die(mysql_error());

答案 3 :(得分:0)

$time_you_want_to_choose = strtotime('previous month');

$ym = date('Y-m', $time_you_want_to_choose);

$query = mysql_query("
          SELECT `id`, `BuyerName`, `BuyerEmail` , `TransactionID`, `DateTime` 
          FROM `order` 
          WHERE `DateTime` like '$ym%'
          LIMIT $start, $per_page
         ");