Help with SQL unions needed
May 10, 2006 12:06 AM
Subscribe
Question for the SQL ninjas in the house. Say you're grabbing data from a bunch of similar tables in a big union. Now say you want the last ten items added anywhere to the database, from any one of those tables. What's the most efficient way to do that?
I've got a working query to pull up similar items from four tables that have similar items. That works great, but I'm concerned when there will be queries pulling hundreds of items from the table, so I'd like to grab say, just the last two items. But how best to do that?
Plain english view of the current query (at the end, it is ordered by date descending to get the most recent stuff at the top):
select stuff from table 1
union
select stuff from table 2
union
...etc
And what I really want in plain english is this:
select top 20 (
select stuff from table 1
union
select stuff from table 2
union
...etc
)
Here's what I've tried and it doesn't work so well:
select top 20 stuff from table 1
union
select top 20 stuff from table 2
union
...etc
It's a horrible waste and the order is all wrong in the output. I'm using Microsoft SQL Server 2000, and nothing I've found online points to working with TOP n records in a union setting.
(this is for MeFi by the way and solving it will help get a major new feature out the door sooner)
posted by mathowie to computers & internet (22 comments total)
posted by Dunwitty at 12:34 AM on May 10, 2006