开发者

Find "missing" records in a bridge/data-intersect table

开发者 https://www.devze.com 2023-01-10 07:10 出处:网络
I\'m generating images from an original and storing them in a table.I want a query that will check for gaps.

I'm generating images from an original and storing them in a table. I want a query that will check for gaps.

The image sizes are kept in a 3rd table, and each original should have开发者_开发问答 1 generated image for each record in the type table.

Where's what I've got so far:

SELECT  oi.OriginalImageID, it.ImageTypeID
FROM    dbo.OriginalImages AS oi
CROSS JOIN
        dbo.ImageType AS it
LEFT OUTER JOIN
            (
            SELECT  oi2.OriginalImageID, it2.ImageTypeID
            FROM    dbo.OriginalImages AS oi2
            INNER JOIN
                    dbo.GeneratedImages AS gi2 ON gi2.OriginalImageID = oi2.OriginalImageID
            INNER JOIN
                    dbo.ImageType AS it2 ON it2.ImageTypeID = gi2.ImageTypeID
            ) AS sub ON sub.OriginalImageID = oi.OriginalImageID
                        AND sub.ImageTypeID = it.ImageTypeID
WHERE   (sub.OriginalImageID IS NULL)

Which works, but it seems very ugly. I'm wondering if there's a more elegant way to do it.

The tables essentially look like this:

OriginalImages
    OriginalImageID (PK)
    Image

GeneratedImages
    OriginalImageID (FK)
    ImageTypeID (FK)
    Image

ImageType
    ImageTypeID (PK)
    Description


You should be able to simplify your existing query to:

SELECT  oi.OriginalImageID, it.ImageTypeID
FROM    dbo.OriginalImages AS oi
CROSS JOIN
        dbo.ImageType AS it
LEFT OUTER JOIN
        dbo.GeneratedImages AS gi2 
        ON gi2.OriginalImageID = oi.OriginalImageID AND
        gi2.ImageTypeID = it.ImageTypeID
WHERE   gi2.OriginalImageID IS NULL

Although personally I would use a NOT EXISTS:

SELECT  oi.OriginalImageID, it.ImageTypeID
FROM    dbo.OriginalImages AS oi
CROSS JOIN
        dbo.ImageType AS it
WHERE NOT EXISTS
        (SELECT NULL FROM dbo.GeneratedImages AS gi2 
         WHERE gi2.OriginalImageID = oi.OriginalImageID  AND
               gi2.ImageTypeID = it.ImageTypeID)

(Edited following comment.)

0

精彩评论

暂无评论...
验证码 换一张
取 消