简体   繁体   中英

In PHP, how do I ask a mySQL database to retrieve multiple most recent records that match a certain value?

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 having clause, combined with a group by , because the group by already selects distinct columns, you can drop the distinct clause.

$user_searchbox_input = mysql_real_escape_string($user_searchbox_input);
$sql = "SELECT candy_type FROM candy_table 
               WHERE candy_vendor LIKE '%$user_searchbox_input%' 
               GROUP BY candy_vendor 
               HAVING timeadded = MAX(timeadded)
               ORDER BY candy_vendor ASC";
$result=mysql_query($sql);

See: http://www.techonthenet.com/sql/having.php

Unfortunately, from those four columns there's no way of telling which record is the most recent.

I would suggest adding a date_time column via the ALTER TABLE command. You can refer to http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for syntax help if you need it.

This won't help you with your current query, but it will help for any future queries.

Sort your data by create_date (ORDER BY) or whatever your create timestamp is and then do SELECT * FROM tbl LIMIT 1; # Retrieve first row

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM