I am having so much trouble with this. I am trying to get the maximum value per day given the range. But I keep getting a blank value in my count column when I load the query result.
<?php
include("dbconnect.php");
$link=Connection();
$data1 = '2016-04-29 00:00:00';
$data2 = '2016-05-02 00:00:00';
$result = mysql_query(
"
SELECT DATE(orderDate), MAX(Count)
FROM testLocation
WHERE orderDate
BETWEEN '$data1%' AND '$data2%'
GROUP BY DATE(orderDate)
"
,$link
);
?>
I suggest you to please use PDO for the above queries.Your question is not fully clear but if you intend to retrieve database result whose value is maximum you can do the following way.
$sql='SELECT * FROM testLocation
WHERE orderDate
BETWEEN '$data1%' AND '$data2%' ORDER BY orderDate
DESC LIMIT 1';
By this query we have limited the retrieved data to be 1 and that is why you will get only the maximum value here and mark we have ordered the data in descending manner.
A few things to look at here.
First, the %
signs in your date constants should not be there. Those only work with the LIKE
operator.
Second, the BETWEEN
operator works poorly for DATETIME
values, because it is the equivalent of this:
WHERE orderDate >= '$data1'
AND orderDate <= '$data2' -- wrong!
This excludes everything after precisely midnight on the ending date. <=
is the wrong comparison to use for DATETIME
.
You should use this instead:
WHERE orderDate >= '$data1'
AND orderDate < '$data2' + INTERVAL 1 DAY
It includes everything up until, but not including, <
midnight on the day after the end date you gave. That means it will include everything on the last day of your date range, which is presumably what you want.
Third, I suggest you give alias column names to the columns in your result set. That will make them easier for php code to retrieve.
SELECT DATE(orderDate) orderDate,
MAX(Count) maxCount
FROM testLocation
WHERE orderDate >= '$data1'
AND orderDate < '$data2' + INTERVAL 1 DAY
GROUP BY DATE(orderDate)
Fourth, if your testLocation
table has no records in it at all for a particular date, the result set from this query will omit that date.
Fifth (others mentioned this in comments) the mysql_
API is not a good choice for your php programming; it's insecure.
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.