tags:

views:

46

answers:

1

I've got a SQL query I fail to improve right now. It works, but it's a bit ugly.

I want to fetch:

  • an id from table A
  • a name from table B

using a WHERE clause which in itself fetches a value from another SQL query.

I would like to replace the following two instances of this SQL query used for the WHERE clause, with one instance:

SELECT intImageGalleryID FROM tblEPiServerCommunityImageGalleryImage
WHERE intID = 123123

How can it be done?

Using SQL Server.

Here's the complete SQL query:

SELECT intID,   
        (SELECT strName
        FROM tblEPiServerCommunityImageGallery
        WHERE intID = 
            (SELECT intImageGalleryID
            FROM tblEPiServerCommunityImageGalleryImage
            WHERE intID = 123123)
            ) as name   
FROM tblEPiServerCommunityClub
    WHERE intImageGalleryID =   
        (SELECT intImageGalleryID
        FROM tblEPiServerCommunityImageGalleryImage
        WHERE intID = 123123)

Thanks!

+2  A: 

You could try below query. I think it is equivalent with your original solution.

SELECT  scc.intID
        , sci.strName
FROM    tblEPiServerCommunityClub scc
        INNER JOIN tblEPiServerCommunityImageGalleryImage scig ON scig.intImageGalleryID = scc.intImageGalleryID
        INNER JOIN tblEPiServerCommunityImageGallery sci ON sci.intID = scig.intImageGalleryID
WHERE   scig.intID = 123123        
Lieven
Thanks Lieven - unfortunately the intId returned is 123123 - the very same in the WHERE clause. How can the actual intImageGalleryId be returned?
Martin S.
@Martin S. It seems I used the wrong alias. Could you retry?
Lieven
It's working! Thank you for that! Now it's up to me trying to understand this :) Cheers!
Martin S.
You might want to read up on joining tables. The scc/scig/sci are mere aliases. They are merely convenient shorthand for your real table names.
Lieven
To maintain the same behaviour as the original query, the join type to `tblEPiServerCommunityImageGallery` should be changed from `INNER JOIN` to `LEFT OUTER JOIN`.
onedaywhen
@onedaywhen, true but I doubt getting an intID *without* a strName is what OP wants.
Lieven
@Lieven: *perhaps* true. The OP declared that his original code "works". My experience of refactoring/porting SQL code tells me to maintain behaviour, warts and all.
onedaywhen