显示最低价格,但按日期和sku分组

时间:2019-04-09 13:25:35

标签: mysql greatest-n-per-group

我正在尝试从MySql数据库中找到一系列产品的最低价格,并按SKU和日期进行分组,然后将其输出到PHP。

我一直在寻找其他答案,但据我所知,只能按1分组,因为我首先需要将所有具有特定日期的产品分组,然后按sku分组并显示每个sku的最低价格

我在数据库中有1个表,该表由

组成
ID  | sku | company     | total_price | date
-------------------------------------------------
1   |tku1 | company_1   | 298.99      |2019/04/09
2   |tku1 | company_2   | 299.99      |2019/04/09
3   |tku1 | company_3   | 290.00      |2019/04/09
4   |stp1 | company_1   | 199.00      |2019/04/09
5   |stp1 | company_2   | 158.99      |2019/04/09
6   |stp1 | company_3   | 150.99      |2019/04/09
7   |upk1 | company_1   | 349.99      |2019/04/09
8   |upk1 | company_2   | 348.99      |2019/04/09
9   |upk1 | company_3   | 346.00      |2019/04/09
10  |dhu1 | company_1   | 520.99      |2019/04/09
11  |dhu1 | company_2   | 518.00      |2019/04/09
12  |dhu1 | company_2   | 515.99      |2019/04/09    
13  |tku1 | company_1   | 298.99      |2019/04/08
14  |tku1 | company_2   | 299.99      |2019/04/08
15  |tku1 | company_3   | 290.00      |2019/04/08
16  |stp1 | company_1   | 199.00      |2019/04/08
17  |stp1 | company_2   | 158.99      |2019/04/08
18  |stp1 | company_3   | 150.99      |2019/04/08
19  |upk1 | company_1   | 349.99      |2019/04/08
20  |upk1 | company_2   | 348.99      |2019/04/08
21  |upk1 | company_3   | 346.00      |2019/04/08
22  |dhu1 | company_1   | 520.99      |2019/04/08
23  |dhu1 | company_2   | 518.00      |2019/04/08
24  |dhu1 | company_2   | 515.99      |2019/04/08

这是我到目前为止所拥有的:-

$sql= ("SELECT * 
        FROM products 
        WHERE total_price = (
                SELECT MIN(total_price) 
                from products 
                GROUP BY sku 
                ORDER BY date");
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['sku'] . "</td>";
echo "<td>" . $row['total_price'] . "</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
}

但这不起作用,我的目标是在php中显示类似的内容

ID  | SKU | COMPANY     | TOTAL_PRICE | DATE
-------------------------------------------------
3   |tku1 | company_3   | 290.00      |2019/04/09
6   |stp1 | company_3   | 150.99      |2019/04/09
9   |upk1 | company_3   | 346.00      |2019/04/09
12  |dhu1 | company_2   | 515.99      |2019/04/09

1 个答案:

答案 0 :(得分:1)

写此查询的最有效方法是使用JOIN到每个total_price的最小sku值的表中:

SELECT p.* 
FROM products p
JOIN (SELECT sku, MIN(total_price) AS total_price
      FROM products 
      GROUP BY sku) mp ON mp.sku = p.sku AND mp.total_price = p.total_price
ORDER BY date

输出:

ID  sku     company     total_price date
3   tku1    company_3   290         2019-04-09
6   stp1    company_3   150.99      2019-04-09
9   upk1    company_3   346         2019-04-09
12  dhu1    company_2   515.99      2019-04-09

Demo on dbfiddle