views:

31

answers:

1

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
+2  A: 

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.)

Mark Bannister
hum, nope. I'm getting the records I need from the original query. but getting no results from either of these. Currently there are 4 "types" so SELECT NULL FROM dbo.GeneratedImages AS gi2 WHERE gi2.OriginalImageID = oi.OriginalImageID will not return null if there is even one of the types in the GeneratedImages table.
Dan Williams
@Dan - Oops, I missed a significant part of the join - try the updated queries.
Mark Bannister
Hot! Thanks for the help, wish I could upvote twice!
Dan Williams