【问题标题】:I need to list the only latest versions of the products with php - mysql我需要用 php - mysql 列出产品的唯一最新版本
【发布时间】:2021-01-26 03:23:44
【问题描述】:

我只是想列出产品的唯一最新版本。并非所有版本都具有相同的产品名称。

所以:

取而代之的是:

*表格不是那么重要,我只是想让代码获取数据。
*表格不是那么重要,我只是想要代码来获取数据。

这是我的代码,但没有列出任何内容:

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'];
}

我的产品表:

【问题讨论】:

  • 在 Select like select DISTINCT(product_name),.... 中尝试DISTINCT

标签: php mysql database datetime greatest-n-per-group


【解决方案1】:

一种选择是使用子查询进行过滤:

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
)

如果你运行的是 MySQL 8.0,你也可以使用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

这假定 product_id 唯一标识每个产品(因此您的表中每个 product_id 会有几行) - 如果不是这种情况,请改用 product_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-30
    • 2013-11-29
    • 2015-04-22
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2017-01-04
    相关资源
    最近更新 更多