SQL Server查询返回相同的行两次

时间:2013-02-12 02:03:38

标签: sql sql-server

我似乎遇到了以下查询的问题。它基本上有效,但我有一个案例,它从mc_WorkoutDetails两次返回一行!

这是原始查询:

ALTER PROCEDURE [dbo].[mc_Workouts_GetActivities]
    @WorkoutID                  bigint
AS
BEGIN
    SET NOCOUNT ON

    SELECT d.ID, a.Description,
            CASE WHEN Reps = 0 THEN NULL ELSE Reps END AS Reps,
            CASE WHEN Sets = 0 THEN NULL ELSE Sets END AS Sets,
            CASE WHEN Minutes = 0 THEN NULL ELSE Minutes END AS Minutes,
            d.Comments, c.Name AS Category, a.CategoryID,
            (CASE WHEN v.ActivityID IS NULL THEN 0 ELSE 1 END) AS HasVideo,
            a.ID AS ActivityID
    FROM mc_WorkoutDetails d
            INNER JOIN mc_Activities a ON d.ActivityID = a.ID
            INNER JOIN mc_Activities_Categories c ON a.CategoryID = c.ID
            LEFT OUTER JOIN mc_TrainerVideos v ON a.ID = v.ActivityID
    WHERE (d.WorkoutID = @WorkoutID)
    ORDER BY SortOrder, a.Description

    RETURN @@ERROR
END

然后我尝试改变:

INNER JOIN mc_Activities a ON d.ActivityID = a.ID
INNER JOIN mc_Activities_Categories c ON a.CategoryID = c.ID

要:

LEFT OUTER JOIN mc_Activities a ON d.ActivityID = a.ID
LEFT OUTER JOIN mc_Activities_Categories c ON a.CategoryID = c.ID

但这似乎没有帮助。我仍然得到重复的行。

有谁能看到发生了什么?

2 个答案:

答案 0 :(得分:2)

您可以做的是使用组将连接添加回同一个表,以清除重复的行。

所以在FROM mc_WorkoutDetails d:

之后将其添加到您的联接中
inner join (select [columns you want to select], max(id) id
            from mc_WorkoutDetails
            group by [columns you want to select] ) q on q.id = d.id

如果这有意义,请告诉我。基本上你正在做一个独特的并获得最大id,所以你消除了连接中的一行。你必须记住,即使你想要重复,它们也会被淘汰,即使它们被认为是在那里。

完全改变是:

ALTER PROCEDURE [dbo].[mc_Workouts_GetActivities]
@WorkoutID                  bigint
AS
BEGIN
SET NOCOUNT ON

SELECT d.ID, a.Description,
        CASE WHEN Reps = 0 THEN NULL ELSE Reps END AS Reps,
        CASE WHEN Sets = 0 THEN NULL ELSE Sets END AS Sets,
        CASE WHEN Minutes = 0 THEN NULL ELSE Minutes END AS Minutes,
        d.Comments, c.Name AS Category, a.CategoryID,
        (CASE WHEN v.ActivityID IS NULL THEN 0 ELSE 1 END) AS HasVideo,
        a.ID AS ActivityID
FROM mc_WorkoutDetails d
inner join (select Reps, Sets, Comments, Minutes, max(id) id
            from mc_WorkoutDetails
            group by Reps, Sets, Comments, Minutes ) q on q.id = d.id
        INNER JOIN mc_Activities a ON d.ActivityID = a.ID
        INNER JOIN mc_Activities_Categories c ON a.CategoryID = c.ID
        LEFT OUTER JOIN mc_TrainerVideos v ON a.ID = v.ActivityID
WHERE (d.WorkoutID = @WorkoutID)
ORDER BY SortOrder, a.Description

RETURN @@ERROR
END

答案 1 :(得分:0)

感谢大家的投入。这里的一般建议是正确的:我在mc_workoutDetails表中有两行引用了mc_Activities表中的同一行。

虽然外键是唯一主键的一部分,但它是一个复合键,因此只要键中的另一列不同,此列就可以包含重复项。