What I’m trying to do is grab entries from an updates table in a mysql database using php. Each entry has a timestamp attached to it. First, I grab 10 distinct dates from the timestamp, create a new array using those 10 unique dates (I do this because the fetchAll put the dates into a multidimensional array), then do another database call grabbing all entries that has those dates. Which can return more than 10 entries. I want it to have 10 distinct dates, not 10 distinct timestamps.
For example, if 2012-03-25 showed up in the first call from distinct dates, it can find:
2012-03-25 00:58:53
2012-03-25 00:58:02
2012-03-25 00:57:20
2012-03-25 00:56:35
2012-03-25 00:55:58
2012-03-25 00:53:20
2012-03-25 00:52:32
2012-03-25 00:51:45
Since the timestamps are different.
Here is the current code I am using, which works.
$test = $dbh->getArray("SELECT DISTINCT DATE_FORMAT(added, '%Y-%m-%d') AS added FROM db_updates ORDER BY added DESC LIMIT 0,10");
foreach ($test as $entry) {
list($date) = $entry;
$output[] = '\''.$date.'\'';
}
$test2 = $dbh->getArray("SELECT * FROM db_updates WHERE DATE_FORMAT(added, '%Y-%m-%d') IN (".implode(',', $output).") ORDER BY added DESC");
print_r($test2);
This returned 33 results.
Just in case anyone ask, I am using PDO and not the mysql function in php. That code is here:
public function getArray($query) {
$result = $this->db->query("$query");
return $result->fetchAll(PDO::FETCH_NUM);
}
This all works 100%, and it does what I want it to do. However, my question is if there is a way to do all this with just a single mysql call, so I don’t have to call twice with a loop in the middle.
I tried to figure it out myself by searching google, and trial and error using joins and such to no avail.
It should work with an
INNER JOIN, and you can just useDATE(added)instead ofDATE_FORMAT()to strip off the time portion of the DATETIME values: