-1

我有表“图像”,如果存在,我想获取主图像,如果不存在,则获取表中的第一行。我用这个:

SELECT Students.Id, Images.ImagePath
FROM Students INNER JOIN    
     Images 
     ON  Students.Id = Images.StudentId 
     AND (   (Images.IsMain = 1) 
          OR (Images.ImagePath = (
              SELECT TOP(1) ImagePath 
              FROM  Images 
              WHERE StudentId = Students.IdId)))
WHERE Students.Id = @StudentId

如果图像中没有“IsMain”,我只会得到一行,但如果有“IsMain”,我会得到两次。

http://sqlfiddle.com/#!3/3ade7/1

4

4 回答 4

2

SELECT  a.*,
        CASE 
            WHEN b.StudentID IS NULL
            THEN c.ImagePath
            ELSE b.ImagePath
        END AS ImagePath
FROM    Students a
        LEFT JOIN
        (
            SELECT  StudentID, ImagePath
            FROM    Images
            WHERE   IsMain = 1
        ) b ON a.ID = b.StudentID
        LEFT JOIN
        (
            SELECT StudentID, ImagePath,
                    ROW_NUMBER() OVER (PARTITION BY  StudentID 
                                    ORDER BY ImagePath ASC) rn
            FROM    Images
        ) c ON c.rn = 1 AND
                a.ID = c.StudentID

更新

更好的一个,

SELECT  a.*,
        c.ImagePath
FROM    Students a
        LEFT JOIN
        (
            SELECT StudentID, ImagePath,
                    ROW_NUMBER() OVER (PARTITION BY  StudentID 
                                    ORDER BY IsMain DESC) rn
            FROM    Images
        ) c ON  c.rn = 1 AND
                a.ID = c.StudentID
-- WHERE    a.ID = 1   -- remove this if you want for specific Student

如果要求学生在表上至少有一条记录Images,则更LEFT JOIN改为INNER JOIN

于 2013-01-21T12:07:08.450 回答
1

您的问题是您选择了 IsMain 图像第一个图像。

以下代码选择第一行,如果存在则为 IsMain 行,否则为顶行。

SELECT Students.Id, Images.ImagePath
FROM Students INNER JOIN    
    Images 
    ON  Students.Id = Images.StudentId 
    AND Images.ImagePath = (
        SELECT TOP(1) ImagePath 
        FROM Images 
        WHERE StudentId = Students.Id
        ORDER BY IsMain DESC) -- This line forces the IsMain image to be the top image returned.
WHERE Students.Id = 1
于 2013-01-21T12:06:48.250 回答
0

怎么样,

SELECT 
            S.Id, 
            COALESCE(MI.ImagePath, OI.ImagePath) ImagePath
FROM 
            Students S
    LEFT JOIN   
            Images MI 
                ON  S.Id = MI.StudentId AND MI.IsMain = 1
    INNER JOIN
            Images OI
            ( 
              SELECT TOP 1 ImagePath 
              FROM  Images 
              WHERE StudentId = Students.IdId
            )
    WHERE
        Students.Id = @StudentId

您应该在子查询中指定 order by,以便知道将选择哪个其他图像。

于 2013-01-21T12:12:35.583 回答
0

为什么所有这些查询都如此复杂,我错过了什么吗?就像获得第一行一样简单

SELECT top (1) Students.Id, Images.ImagePath
FROM Students INNER JOIN    
     Images 
     ON  Students.Id = Images.StudentId 
WHERE Students.Id = 1
order by case when Images.IsMain = 1  then 1 else 0 end desc 
--order by Images.IsMain = 1  
于 2013-01-21T12:15:11.670 回答