I am trying to get the calculated result, how many were sold in January, February from one query.
$query = "SELECT COUNT(id) FROM tableName WHERE status='sold' AND YEAR(FROM_UNIXTIME(
date )) = '$year' AND MONTH(FROM_UNIXTIME(
date )) = '1', status='sold' AND YEAR(FROM_UNIXTIME(
date )) = '$year' AND MONTH(FROM_UNIXTIME(
date`)) = '2'";
In order to compute aggregate values you have to use GROUP BY
SELECT EXTRACT(YEAR_MONTH FROM `date`) AS year_month, COUNT(*) AS cnt
FROM tableName
WHERE `status` = 'sold'
GROUP BY EXTRACT(YEAR_MONTH FROM `date`)
Keep in mind that, because of the function EXTRACT()
used in the GROUP BY
clause, MySQL cannot use an index to optimize the processing of the GROUP BY
and, if the WHERE
condition selects a large number of rows the query will be slow.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.