我想从特定月份的mysql表中获取结果。我写查询但查询不正常。有人可以帮忙吗?
$sql = "SELECT sum(size) as size FROM tb_size WHERE MONTH(date_created) = '" . mysqli_real_escape_string($db, "Oct") . "' AND YEAR(date_created) = YEAR(CURRENT_DATE()";
$query = mysqli_query($db, $sql);
$result = mysqli_fetch_object($query);
$size = $result->size;
echo $size;
答案 0 :(得分:1)
MONTH()
会返回一个数字。所以你的查询应该是这样的:
SELECT sum(size) as size
FROM tb_size
WHERE MONTH(date_created) = 10 AND YEAR(date_created) = YEAR(CURRENT_DATE();
如果您希望Oct
匹配,则可以改为使用DATE_FORMAT()
:
SELECT sum(size) as size
FROM tb_size
WHERE DATE_FORMAT(date_created, '%b') = 'Oct' AND YEAR(date_created) = YEAR(CURRENT_DATE();
答案 1 :(得分:0)
如上所述 - Month
会返回一个数字:https://www.w3resource.com/mysql/date-and-time-functions/mysql-month-function.php
您可以使用MonthName
:https://www.w3resource.com/mysql/date-and-time-functions/mysql-monthname-function.php,但会返回一个全名(十月),而不是您正在使用的十月。
您还可以使用DATE_FORMAT(date_created, '%b')
获取短月名称