3

我似乎在使用以下查询时遇到了问题。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

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

谁能看到发生了什么?

4

2 回答 2

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
于 2013-02-12T02:13:20.990 回答
0

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

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

于 2013-02-12T02:55:18.377 回答