我有一个Product表,一个Category表,以及它们之间的交叉引用/映射表。 产品可以属于多个类别。 我想要一个查询来生成产品ID和类别名称。 由于产品可以属于多个类别,我希望只包含一个等于Product_Category_Mapping.DisplayOrder中最低值的产品。
以下是三个表格中有限的样本数据集
Table: Product PC_Mapping Category
Column:(ID) (DispOrd) (Name)
Records
----------------------------------
1 10 Milk <----- just return this row
1 20 Dairy
1 30 Cheese
答案 0 :(得分:1)
@John:我认为您的查询几乎不需要修改。我认为Chad想要为每个产品选择最低价值,因此应该添加一个分组。
SELECT p.ID as [Product ID], c.Name as Category, m.x
FROM Product p INNER JOIN (
SELECT ProductID, Min(DisplayOrder) as x FROM Product_Category_Mapping GROUP BY ProductId) m ON p.ID = m.ProductID
INNER JOIN Product_Category_Mapping pc ON p.ID = pc.ProductID AND m.x = pc.DisplayOrder
INNER JOIN Category c ON pc.CategoryID = c.ID
答案 1 :(得分:0)
我认为应该这样做,尽管可能有更简单的答案:
SELECT p.ID as [Product ID], c.Name as Category
FROM Product p INNER JOIN (
SELECT ProductID, Min(DisplayOrder) as x FROM Product_Category_Mapping) m ON p.ID = m.ProductID
INNER JOIN Product_Category_Mapping pc ON p.ID = pc.ProductID AND m.x = pc.DisplayOrder
INNER JOIN Category c ON pc.CategoryID = c.ID