Let's say I have two tables of books and two tables of their corresponding editions.
I have a query as follows:
SELECT TOP 10 * FROM
(SELECT hbID, hbTitle, hbPublisherID, hbPublishDate, hbedID, hbedDate
FROM hardback
LEFT JOIN hardbackEdition on hbID = hbedID
UNION
SELECT pbID, pbTitle, pbPublisher, pbPublishDate, pbedID, pbedDate
FROM paperback
Left JOIN paperbackEdition on pbID = pbedID
) books
WHERE hbPublisherID = 7
ORDER BY hbPublishDate DESC
If there are 5 editions of the first two hardback and/or paperback books, this query only returns two books. However, I want the TOP 10
to apply only to the number of actual book records returned. Is there a way I can select 10 actual books, and still get all of their associated edition records?
In case it's relevant, I do not have database permissions to CREATE and DROP temporary tables.
Thanks for reading!
Update
To clarify: The paperback table has an associated table of paperback editions. The hardback table has an associated table of hardback editions. The hardback and paperback tables are not related to each other except to the user who will (hopefully!) see them displayed together.
If I understand you correctly, you could get the 10 books with all associated editions by
WITH
statement to return the initial, complete resultsetGROUP BY
JOIN
the results of this group to retain all information from given 10 books.SQL Statement
or if you prefer to write the where clause only once
This should grab the ten most recently published titles with a hardback from publisher 7:
Not so easy. You need to apply Top 10 to only the hardback and paperback tables, without the join. Then join the result to the data.
The following query only works when the hbID and pbID are always unique. If not, it gets more complicated. You need to separate them or add another column to the query to distinguish them.