SQL查询:当前产品的最低价格

时间:2013-08-12 06:49:41

标签: mysql sql

我正在为项目编写SQL查询。

提供以下表格:

tblProduct => (proProductID, proProductName)
tblSeller => (selSellerID, selSellerName)
linkProductSeller => (linkID, linkProductID, linkSellerID, linkPrice, linkShippingPrice, linkDatetime)

每次产品的价格/运费在卖家处更改时,都会添加linkProductSeller中的新行。

我需要知道产品的当前最低价格/运费组合和卖家。

要获取产品的所有当前价格,我使用此查询

SELECT linkProductID, linkSellerID, linkPrice+linkShippingPrice as price, linkDatetime
FROM linkProductSeller AS a
WHERE linkDatetime = (
    SELECT MAX(linkDatetime)
    FROM linkProductSeller AS b
    WHERE a.linkProductID = b.linkProductID
AND a.linkSellerID = b.linkSellerID)
ORDER BY linkProductID ASC, price ASC, linkDatetime DESC

感谢您的支持。

2 个答案:

答案 0 :(得分:1)

您需要的所有数据都在linkProductSeller中,因此这应该可以使用

select l.linkProductId, min(linkPrice + linkShippingPrice) as minPrice
  from linkProductSeller l,
       (select linkProductID, linkSellerId, max(linkDateTime) as linkDateTime
          from linkProductSeller 
         group by linkProductID, linkSellerId) m
 where l.linkProductID = m.linkProductID
   and l.linkSellerID = m.linkSellerID
   and l.linkDateTime = m.linkDateTime
 group by linkProductId

答案 1 :(得分:0)

我猜,上面的答案并不完全正确。如果您需要产品和销售商的名称,并且确切地说价格何时改变(您只需要当前价格)并不重要,那么,我想,您需要这样的东西:

select 
    p.proProductID, 
    p.proProductName, 
    s.selSellerID, 
    s.selSellerName, 
    min(l.linkPrice + l.linkShippingPrice) as Price
  from 
    tblProduct p,
    tblSeller s,
    (select * from linkProductSeller 
    where (linkProductID, linkSellerID, linkDateTime) 
    in 
        (select linkProductID, linkSellerID, max(linkDateTime) from linkProductSeller 
        group by linkProductID, linkSellerID 
        having linkDateTime = max(linkDateTime)) l
where 
    p.proProductID= l.linkProductID
    and s.selSellerID= m.linkSellerID
group by 
    p.proProductID, 
    p.proProductName, 
    s.selSellerID, 
    s.selSellerName