确定,
我有一个表发布,它有PublicationID,PublisherID,NameAbbrev ...并且它连接到另一个名为AreaBuy的表,它有一个AreaBuyID字段,NameAbbrev,DateCreated和CreatedBy字段。这种关系基本上是公司为我们的产品签署了一组论文(不一定由同一家伞公司拥有)。发布和AreaBuy表是通过PublicationAreaBuy表连接的,该表具有1 ... M ... 1的关系(巧妙的名称对!)。
我的问题是:我想从发布表中选择一组出版物,假设我们在今年第一天到现在之间签署了这些出版物,但如果返回的任何论文都在AreaBuy组中,我想要的也回来了!踢球者,我只想返回两列,这将是所有发布ID和名称,所以我希望AreaBuy信息包含在这两列中。所以我要说我在我的集合中得到五个结果:
idNum | name 1 The Herald 2 L A Times 162 L A Area Buy 230 County Enquirer 2006 Illinois Post
所以,LA时代是在洛杉矶地区购买,所以也出现了 - 你是怎么做到的?将一组结果信息合并到另一组中?
对不起,这是一个糟糕的解释,R。
答案 0 :(得分:0)
好的,我想我会按照您的需要进行操作。我觉得这样的事情可以解决问题。
SELECT Publication.PublicationID, Publication.NameAbbrev
FROM Publication
UNION ALL
SELECT AreaBuy.AreaBuyID, AreaBuy.NameAbbrev
FROM AreaBuy
INNER JOIN PublicationAreaBuy
ON AreaBuy.AreaBuyID = PublicationAreaBuy.AreaBuyID
INNER JOIN Publication
ON PublicationAreaBuy.PublicationID = Publication.PublicationID
根据需要添加DateCreated的钩子或任何其他判别。
答案 1 :(得分:0)
很难说,解释不太清楚,但你肯定想要使用连接。从阅读你的问题来看,这是我能得到的最接近你想要的东西。
SELECT P.PublicationID, P.Name
From Publication P
LEFT JOIN PublicationAreaBuy AS PAB
ON P.PublicationID = PAB.PublicationID
LEFT JOIN AreaBuy AS AB
ON PAB.AreaBuyID = AB.AreaBuyID
WHERE P.SignedUp > @firstDayOfYear
OR Not AB.AreaBuyID is NULL
这将返回在一年的第一天之后注册的所有发布的PublicationID和发布名称,或者它们是否在PublicationAreaBuy表中。
答案 2 :(得分:0)
这实际上是一个支点,但它最容易表示为两个不同集合的UNION
- 出版物集和它们所链接的区域集。正常的UNION
去除了集合,所以通常会慢一点。 UNION ALL
可能会产生多个区域,因为两个出版物位于同一区域,因此如果您使用DISTINCT
,则需要UNION ALL
来停止重复项:
SELECT 'Publication' AS RowType
,Publication.PublicationID AS idNum
,Publication.NameAbbrev AS name
FROM Publication
WHERE Publication.SignedUp >= '1/1/2009'
UNION ALL
SELECT DISTINCT 'Area' AS RowType
,AreaBuy.AreaBuyID AS idNum
,AreaBuy.NameAbbrev AS name
FROM AreaBuy
INNER JOIN PublicationAreaBuy
ON AreaBuy.AreaBuyID = PublicationAreaBuy.AreaBuyID
INNER JOIN Publication
ON PublicationAreaBuy.PublicationID = Publication.PublicationID
WHERE Publication.SignedUp >= '1/1/2009'
或使用UNION
:
SELECT 'Publication' AS RowType
,Publication.PublicationID AS idNum
,Publication.NameAbbrev AS name
FROM Publication
WHERE Publication.SignedUp >= '1/1/2009'
UNION
SELECT 'Area' AS RowType
,AreaBuy.AreaBuyID AS idNum
,AreaBuy.NameAbbrev AS name
FROM AreaBuy
INNER JOIN PublicationAreaBuy
ON AreaBuy.AreaBuyID = PublicationAreaBuy.AreaBuyID
INNER JOIN Publication
ON PublicationAreaBuy.PublicationID = Publication.PublicationID
WHERE Publication.SignedUp >= '1/1/2009'
在支持公用表表达式的SQL方言中,您可以通过执行以下操作来避免重复更复杂的业务逻辑:
WITH SelectedPubs AS (
SELECT Publication.PublicationID
,Publication.NameAbbrev
FROM Publication
WHERE Publication.SignedUp >= '1/1/2009'
)
SELECT 'Publication' AS RowType
, SelectedPubs.PublicationID AS idNum
,SelectedPubs.NameAbbrev AS name
FROM SelectedPubs
UNION
SELECT 'Area' AS RowType
,AreaBuy.AreaBuyID AS idNum
,AreaBuy.NameAbbrev AS name
FROM AreaBuy
INNER JOIN PublicationAreaBuy
ON AreaBuy.AreaBuyID = PublicationAreaBuy.AreaBuyID
INNER JOIN SelectedPubs
ON PublicationAreaBuy.PublicationID = SelectedPubs.PublicationID