views:

145

answers:

4

Scenario

I'm using SQL Server 2005 I have a T-Sql query that has multiple criteria to search on the WHERE clause. I'm certain that I'm doing this in a very inefficient and long way round. How can I ensure that I don't have to manually type out all the criteria? Instead I want to pass in the criteria via a SELECT * clause.

Current Query Code

SELECT * FROM tblBooks
WHERE BookID = 1
OR BookID = 4
OR BookID = 5
OR BookID = 7
OR BookID = 8
OR BookID = 11
OR BookID = 14

Proposed PSEUDO Query Code

SELECT * FROM tblBooks
WHERE BookID = (SELECT BookID FROM tblAuthors WHERE Genre = 'Fiction') 

Comments On Code

As you can see from the proposed pseudo code, the idea is to select a list of BookIDs from another query and pass this list of criteria into the actual query itself. How do I go about doing this correctly?

Help greatly appreciated.

+2  A: 

Use a join:

SELECT  b.*
FROM    tblBooks b
        INNER JOIN
                tblAuthors a
                ON b.BookID = a.BookID
WHERE   a.Genre = 'Fiction'

I assume these are not your real tables? I can't see why the Genre property is not on the book itself. Many authors write across multiple genres (take Iain Banks for example).

David M
Books are in genres **and** authors write in genres, so I would have genres be a table of it's own with join tables between both books and genres (assuming a book can be in multiple genres even if that's not typical) and authors and genres.
tvanfosson
Yes, certainly a separate lookup table for genres would be sensible, with a link table between authors and genres. Not sure about books...
David M
+3  A: 

are you looking for something like this

SELECT * FROM tblBooks
WHERE BookID in (SELECT BookID FROM tblAuthors WHERE Genre = 'Fiction') 

This will return all the data in the table tblAuthors if book id is there

anishmarokey
+3  A: 

YOur pseudo code, isn't too pseudo. Change the = to IN and your done.

SELECT * FROM tblBooks 
WHERE BookID IN (SELECT BookID FROM tblAuthors WHERE Genre = 'Fiction')
Ralph Shillington
+4  A: 

Just throwing alternatives out there:

SELECT tblBooks.* 
  FROM tblBooks 
 WHERE EXISTS (SELECT *
                 FROM tblAuthors 
                WHERE tblBooks.BookID = tblAuthors.BookID
                  AND tblAuthors.Genre = 'Fiction');

SELECT tblBooks.*
  FROM tblBooks
 WHERE tblBooks.BookID = ANY
(SELECT tblAuthors.BookID
   FROM tblAuthors
  WHERE tblAuthors.Genre = 'Fiction');
Ardman