MySQL查找多个相同产品的最低价格行

时间:2018-05-14 08:29:09

标签: mysql aggregate

我的产品表有许多相同的产品,但条件不同,供应商/供应商不同,我希望得到价格最便宜的产品和其他数据。

这里有一些条目

+----------+--------------------+-----------+------------+------------+--------------+-------------+
|    ID    |    Product Name    | new_price | old_price  |    price   |  provider_id |  condition  |
+----------+--------------------+-----------+------------+------------+--------------+-------------+
|    1     |   samsung tv 32    |   1200    |    null    |    null    |       2      |     new     |
|    2     |   samsung tv 32    |    null   |    null    |     800    |      123     | refurbished |
|    23    |   samsung tv 32    |    null   |     300    |    null    |       6      |     used    |
|    48    |   samsung tv 32    |   1500    |    null    |    null    |       8      |     new     |
|    2     |    smart watch     |    null   |    null    |     200    |      123     | refurbished |
|    23    |    smart watch     |    null   |     100    |    null    |       6      |     used    |
+----------+--------------------+-----------+------------+------------+--------------+-------------+

欲望结果

+----------+--------------------+-----------+--------------+-------------+
|    ID    |    Product Name    |   price   |  provider_id |  condition  |
+----------+--------------------+-----------+--------------+-------------+
|    23    |   samsung tv 32    |    300    |       6      |     used    |
|    23    |    smart watch     |    100    |       6      |     used    |
+----------+--------------------+-----------+--------------+-------------+

这是我的疑问,我累了。

SELECT
    MIN(
        IF(
            new_price > 0,
            new_price,
            IF(
                old_price > 0,
                old_price,
                IF(
                    price > 0,
                    price,
                    0
                )
            )
        )
    ) AS price,
    `name`,
    `id`,
    `provider_id`
FROM
    `products`
GROUP BY
    `name`

1 个答案:

答案 0 :(得分:0)

要获得所需的结果集,您可以使用coalesce的自联接来获得第一个非空值。

select p.ID,
p.name,
coalesce(p.`new_price`, p.`old_price`, p.`price`) as price,
p.provider_id,
p.condition
from products p
left join products p1 on p.name  = p1.name 
and coalesce(p.`new_price`, p.`old_price`, p.`price`) > coalesce(p1.`new_price`, p1.`old_price`, p1.`price`)  
where p1.ID is null

Demo

使用join

获得相同结果的另一种方法
select p.ID,
p.name,
coalesce(p.`new_price`, p.`old_price`, p.`price`) as price,
p.provider_id,
p.condition
from products p
join (
  select name, min(coalesce(`new_price`, `old_price`,`price`)) as price
  from products
  group by name
) p1 on p.name  = p1.name 
and coalesce(p.`new_price`, p.`old_price`, p.`price`) = p1.price

Demo