如果不存在,则存在“和”条件的内部联接

时间:2013-01-21 11:59:24

标签: sql sql-server-2008 tsql select

我有表'图像'我想要获得主图像(如果存在),如果不存在,则获取表格中的第一行。我用这个:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

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

答案 3 :(得分: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