You have a scoping issue. A union combines two separate queries. So if you separate your queries out:
SELECT PublicationID
FROM ( SELECT DISTINCT pat.PublicationID
FROM dbo.PubAdvTransData AS pat
INNER JOIN dbo.PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '7 / 1 / 2009') AND (pat.PublicationID = 29171)
) AS table1
SELECT PublicationAreaBuy.AreaBuyID AS PublicationID
FROM PublicationAreaBuy
INNER JOIN table1 AS table1_1
ON table1.publicationID = PublicationAreaBuy.PublicationID
You can see that in the second query there's no such thing as table1. There are a few other ways to accomplish what you're trying to do:
- duplicate the subquery (ugly)
- use a Common Table Expression (only if this is T-SQL)
- use a #temporary @table (again, I only know how to do this in T-SQL)
If we were to duplicate the subquery, it'd look like this. However, the top query has no conditions, so it doesn't need to be a subquery:
SELECT DISTINCT pat.PublicationID
FROM dbo.PubAdvTransData AS pat
INNER JOIN dbo.PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '7 / 1 / 2009') AND (pat.PublicationID = 29171)
UNION
SELECT PublicationAreaBuy.AreaBuyID AS PublicationID
FROM PublicationAreaBuy
INNER JOIN ( SELECT DISTINCT pat.PublicationID
FROM dbo.PubAdvTransData AS pat
INNER JOIN dbo.PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '7 / 1 / 2009') AND (pat.PublicationID = 29171)
) AS table1
ON table1.publicationID = PublicationAreaBuy.PublicationID