Search code examples
phpmysqldatabasedatetimegreatest-n-per-group

I need to list the only latest versions of the products with php - mysql


I'm just trying to list the only latest versions of the products. Not all versions with the same product name.

So this: enter image description here

Instead of this: enter image description here

*tables are not so important I just want the code to get the data.
*tables are not so important I just want the code to get the data.

This is my code but lists nothing :

include("databaseinfo.php");
$sql = "SELECT product_name,release_date,version FROM product GROUP BY product_name ORDER BY product_ID DESC";
$result = mysqli_query($conn,$sql);
while ($b=mysqli_fetch_array($result,MYSQLI_ASSOC)){
    echo $b['product_name']." ".$b['release_date']." ".$b['version'];
}

My product table:

enter image description here


Solution

  • One option is to filter with a subquery:

    select product_name, release_date, version
    from product p
    where release_date = (
        select max(p1.release_date)
        from product p1
        where p1.product_id = p.product_id
    )
    

    If you are running MySQL 8.0, you can also use rank():

    select product_name, release_date, version
    from (
        select p.*, rank() over(partition by product_id order by release_date desc)
        from product
    ) t
    where rn = 1
    

    This assumes that product_id uniquely identifies each product (so your table would have several rows per product_id) - if that's not the case, use product_name instead.