MYSQL - 从表格中逐个产品获得最低出价(结果很奇怪)

时间:2013-05-14 08:07:07

标签: mysql sql

好的,我对我的查询发生了什么感到困惑,但我想要做的是以下内容: 获取按product_id分组的最低出价,然后加载与该出价相关的产品信息。

目前,当运行以下查询时,它告诉我,bid_id列其中product_id = 2的列为30但其绝对不是30,它应该是120(尽管bid_price值在29.99处是正确的):

SELECT lowbid.bid_id, lowbid.bid_price
FROM (SELECT bid_id, min(bid_price) AS bid_price, product_id FROM tbl_products_bid WHERE is_active = 1 AND is_deleted = 0 GROUP BY product_id) AS lowbid;

现在由于这个查询给了我随机的bid_id,我不知道为什么我想知道一个SQL大师是否可以为我提供一个洞察1.如果我是完全厚或2.如果有另一种方式或为什么我可以得到随机bid_id甚至与bid_price无关。

我已经创建了一个SQLFiddle,可以解释我的意思,但任何帮助都会感激不尽。

http://sqlfiddle.com/#!2/de77b/14

也只是为了让你知道这个查询是另一个查询的一部分,但我拿出了我认为给我一个问题的元素(即上面) 更大查询的部分如下:

SELECT lowestbid.bid_id, lowestbid.product_id, lowestbid.bid_price as seller_bid_price, seller_description, pb.is_countdown, pb.startdate, pb.enddate
FROM
  tbl_products_bid pb
  inner JOIN (
    SELECT bid_id, product_id, min(bid_price) as bid_price, seller_id, description as seller_description, is_countdown, startdate, enddate from tbl_products_bid where is_active = 1 group by product_id
  ) AS lowestbid ON pb.bid_id = lowestbid.bid_id
order by lowestbid.bid_price asc

1 个答案:

答案 0 :(得分:2)

SELECT  a.*
FROM    tbl_products_bid a
        INNER JOIN
        (
            SELECT  product_id, MIN(bid_price) min_price
            FROM    tbl_products_bid
            GROUP   BY product_id
        ) b ON  a.product_id = b.product_id AND
                a.bid_price = b.min_price