I have a table that has the following fields:
candy_name
candy_type
candy_amount
candy_vendor
One candy_type can have multiple candy_names, like “gummis” might have “orange,” “watermelon,” “sour watermelon,” and so on.
What I am doing is searching this table by vendor, and then I want to see the most recent entry for each unique candy_type (ignoring candy_name). That is, the most recently added row for each unique candy_type.
So I found out how to do the part about finding all the unique candy_types in that table:
$sql = "SELECT DISTINCT candy_type FROM candy_table
WHERE candy_vendor LIKE '%$user_searchbox_input%'
ORDER BY candy_vendor ASC";
$result=mysql_query($sql);
Now I need to find out how to retrieve the MOST RECENT record for each unique candy_type.
Like for the candy_type of “gummi,” if the last record matching that type was “orange,” that’s the one I want to see—not the others.
And for the candy_type of “chocolate,” if the last matching record was “milk,” I don’t care about the others, but I want to retrieve that most recent record matching that candy_type.
How do I do that?
If you want the most recent, use a
havingclause, combined with agroup by, because the group by already selects distinct columns, you can drop thedistinctclause.See: http://www.techonthenet.com/sql/having.php