SQL内部连接和重复

时间:2015-10-29 12:57:47

标签: sql sql-server join

当我运行SQL查询时,我得到了不必要的重复项。在我的查询中,我将列出(5)作为以下示例添加的最新产品。

产品可以分配多个类别,例如:

- Product A, Category "men > clothes > pants"
- Product A, Category "women > clothes > pants"
- Product B, Category "men > clothes > shirts"
- Product B, Category "women > clothes > shirts"

运行我的SQL查询会给我输出:

- Product A
- Product A
- Product B
- Product B

我想要的只是:

- Product A (Category "men > clothes > pants")
- Product B (Category "men > clothes > shirts")

产品表
产品ID
产品名称
类别联接表

JoinID
的ProductID
Category3ID
Category3表
Category3ID
Category2ID
Cat3Name
Category2表
Category2ID
Category1ID
Cat2Name
Category1表
Category1ID
Cat1Name

SELECT TOP 5 * FROM Product P
INNER JOIN Product_Category_Join PCJ ON (P.ProductID = PCJ.ProductID)
INNER JOIN Category3 C3 ON (PCJ.Category3ID = C3.Category3ID)
INNER JOIN Category2 C2 ON (C3.Category2ID = C2.Category2ID)
INNER JOIN Category1 C1 ON (C2.Category1ID = C1.Category1ID)
ORDER BY P.Date DESC

1 个答案:

答案 0 :(得分:2)

删除重复项的一种简单方法是使用CTE(common-table-expression)和ROW_NUMBER函数。它的优点是,您可以根据需要选择所有列:

WITH CTE AS
(
    SELECT  *, RN = ROW_NUMBER() OVER (PARTITION BY P.ProductID ORDER BY P.Date DESC)
    FROM Product P
    INNER JOIN Product_Category_Join PCJ ON (P.ProductID = PCJ.ProductID)
    INNER JOIN Category3 C3 ON (PCJ.Category3ID = C3.Category3ID)
    INNER JOIN Category2 C2 ON (C3.Category2ID = C2.Category2ID)
    INNER JOIN Category1 C1 ON (C2.Category1ID = C1.Category1ID)
)
SELECT TOP 5 * 
FROM CTE
WHERE RN = 1
ORDER BY Date DESC