查询 - 最小(成本)并显示该成本的供应商

时间:2017-07-04 18:19:18

标签: mysql

我一直坚持使用MySQL查询。该表是:

CREATE TABLE items_costs (
  UPC varchar(15) NOT NULL,
  SupplierID int(11) NOT NULL,
  Current_as_of_Date datetime DEFAULT NULL,
  Cost1 float DEFAULT NULL,
  Cost2 float DEFAULT NULL,
  Cost3 float DEFAULT NULL,
  MSRP float DEFAULT NULL,
  MAP float DEFAULT NULL,
  Unique_Entry_Id datetime DEFAULT NULL,
  PRIMARY KEY (UPC,SupplierID),
  KEY SupplierID (SupplierID),
  CONSTRAINT items_costs_ibfk_1 FOREIGN KEY (UPC) REFERENCES items (UPC),
  CONSTRAINT items_costs_ibfk_2 FOREIGN KEY (SupplierID) REFERENCES suppliers (SupplierID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8`

我为每件商品获得最低的Cost1,Cost2,Cost3:

MIN(LEAST(IFNULL(ic.Cost3, ic.Cost1), IFNULL(ic.Cost2, ic.Cost1), ic.Cost1)) AS Cost

但是,现在我需要将SupplierID与特定成本

相关联

我试过了:

SELECT 
    ic.UPC,
    ic.SupplierID,
    ic.Current_as_of_Date,
    ic.Cost1 AS Cost,
    ic.MSRP,
    ic.MAP,
    s.SupplierName,
    s.Map_YN AS Supplier_MAP
FROM
    items_costs AS ic
        JOIN
    suppliers AS s ON s.supplierId = ic.SupplierID
WHERE
    (ic.upc , ic.Cost1) IN (SELECT 
            ic_min.UPC,
                MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                        IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
        FROM
            items_costs ic_min
        GROUP BY ic_min.UPC))

...按照其他线程的建议,通过UPC给出最低的成本。但是,仍然会获得重复的UPC,这应该是唯一的。

我在这里做错了什么?

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可以使用DISTINCT

    SELECT DISTINCT 
      ic.UPC,
      ic.SupplierID,
      ic.Current_as_of_Date,
      ic.Cost1 AS Cost,
      ic.MSRP,
      ic.MAP,
      s.SupplierName,
      s.Map_YN AS Supplier_MAP
  FROM items_costs AS ic
  JOIN suppliers AS s ON s.supplierId = ic.SupplierID
  WHERE  (ic.upc , ic.Cost1) IN (
      SELECT 
              ic_min.UPC,
              MIN(LEAST(IFNULL(ic_min.Cost3, ic_min.Cost1),
                      IFNULL(ic_min.Cost2, ic_min.Cost1),
                        ic_min.Cost1)) AS Cost
          FROM items_costs ic_min
          GROUP BY ic_min.UPC))

答案 1 :(得分:0)

感谢您的帮助!

我在这里找到了答案,这似乎是一个常见的问题:https://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html

SELECT 
ic1.upc,
ic1.supplierid,
ic1.MSRP,
ic1.MAP,
ROUND((LEAST(IFNULL(ic1.Cost3, ic1.Cost1),
                IFNULL(ic1.Cost2, ic1.Cost1),
                ic1.Cost1)),
        2) AS Cost,
s.SupplierName,
s.Map_YN AS Supplier_MAP
FROM
items_costs AS ic1

    JOIN
suppliers AS s ON s.supplierid = ic1.supplierid

WHERE
ic1.cost1 = (SELECT 
        MIN(ic2.cost1)
    FROM
        items_costs AS ic2
    WHERE
        ic1.upc = ic2.upc)