这是我的问题:
SELECT publicationId AS PublicationID
FROM dbo.PublicationOwner
WHERE ownerId = 31331
UNION
SELECT AreaBuy.AreaBuyID AS PublicationID
FROM AreaBuy
JOIN PublicationAreaBuy ON AreaBuy.AreaBuyID = PublicationAreaBuy.AreaBuyID
WHERE PublicationAreaBuy.PublicationID IN (SELECT publicationId
FROM dbo.PublicationOwner
WHERE ownerId = 31331)
ORDER BY publicationId
我想做的是:
获取所有者ID等于31331的发布ID列表,如果区域购买表中的发布ID在第一个查询的结果中,则添加(联合)任何isabuy id(作为发布ID)。 / p>
有什么问题?是的,31331是正确的所有者ID,并确实返回一个发布ID,该ID也在区域购买表中。
答案 0 :(得分:1)
看起来像经典的混音。我没有看到属性publicationId和AreaBuyId之间有任何相似之处。 它们可能只是非常糟糕的列:-)。这种不同属性的结合似乎不是正确的方法。
为什么不:
SELECT O.publicationId , A,AreaBuyId
FROM dbo.PublicationOwner O
LEFT OUTER JOIN dbo.AreaBuy A
ON O.AreaBuyId = A.AreaBuyId
WHERE OwnerId =31331
找到你想要的东西?
答案 1 :(得分:0)
我喜欢这种递归CTE的想法,因为我们想要添加到原始列表中。
DECLARE @ownerid INT;
SET @ownerid = 31331;
WITH Publications AS
(
SELECT publicationId AS PublicationID, 'P' AS Rowtype
FROM dbo.PublicationOwner
WHERE ownerId = @ownerid
UNION ALL
--Note, I am not using the AreaBuy table, because the info is in PublicationAreaBuy
SELECT a.AreaBuyID, 'A' AS Rowtype
FROM Publications AS p
JOIN PublicationAreaBuy AS a
ON a.PublicationID = p.PublicationID
)
SELECT *
FROM Publications
ORDER BY PublicationID
;
并且......执行连接将停止IN子句中的NULL问题。
编辑:下一个查询将在SQL 2005之前的版本中运行
DECLARE @ownerid INT
SET @ownerid = 31331
SELECT publicationId AS PublicationID, 'P' AS Rowtype
FROM dbo.PublicationOwner
WHERE ownerId = @ownerid
UNION ALL
--Note, I am not using the AreaBuy table, because the info is in PublicationAreaBuy
SELECT a.AreaBuyID, 'A' AS Rowtype
FROM (
SELECT publicationId AS PublicationID, 'P' AS Rowtype
FROM dbo.PublicationOwner
WHERE ownerId = @ownerid
) AS p
JOIN PublicationAreaBuy AS a
ON a.PublicationID = p.PublicationID
ORDER BY PublicationID