SQL联合问题
这是我的查询:
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(作为出版物 id)(如果区域购买表中的出版物 id)在第一个查询的结果中。
怎么了?是的,31331 是正确的所有者 ID,并且确实返回了也在区域购买表中的出版物 ID。
Here is my query:
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
What I am trying to do is:
Get the list of publication ID's where the owner id is equal to 31331 and add in (union) any areabuy ids (as publication id) if the publication id in the area buy table are in the results from the first query.
What is wrong? And yes, 31331 is the correct owner id and does return a publication ID which is also in the area buy table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来像是经典的混搭。我没有看到属性 PublicationId 和 AreaBuyId 之间有任何相似之处。
可能它们只是命名非常糟糕的列:-)。将如此不同的属性结合起来似乎并不是正确的方法。
为什么不:
得到你想要的东西?
Looks like a classic mix up. I dont see any similarity between attributes publicationId and AreaBuyId.
It could be they are just very badly named columns :-). A union of such different attributes doesnt seem like the right way to go.
Why doesnt :
Get you what you want?
我喜欢为此使用递归 CTE 的想法,因为我们想要添加到原始列表中。
并且...执行连接将阻止 IN 子句中 NULL 的任何问题。
编辑:下一个查询将在 SQL 2005 之前的版本中运行
I like the idea of a recursive CTE for this, since we want to add to the original list.
And... doing a join will stop any problems with NULLs in your IN clause.
Edit: This next query will work in versions prior to SQL 2005