2016-08-19 51 views
1

我已经达到了我的查询编写专业知识的极限。 我有以下表中EXTID的组合+ extdt我们一种复合键的:SQL当外键2出现在第二个表中时,查找具有外键1的所有行

ents 
entid | extid | extdt  | itemid | 
======================================= 
    1000 | 100 | '2016-08-01' | 1 | 
    1001 | 100 | '2016-08-01' | 2 | 
    1002 | 200 | '2016-08-01' | 3 | 
    1003 | 100 | '2016-08-02' | 4 | 
    1004 | 200 | '2016-08-02' | 5 | 
    1005 | 100 | '2016-08-02' | 6 | 

所以,如果商品ID(1或2)中的项目表,查询将返回两行1000和1001如果itemid的3存在,列1002返回等等​​...

items 
    itemid | itemDesc | 
    =================== 
     1 | 'fu' | 
     3 | 'bar' | 
     4 | 'blah' | 

随着上述项目表,我希望回去:

entid | extid | extdt  | itemid | 
======================================= 
    1000 | 100 | '2016-08-01' | 1 | 
    1001 | 100 | '2016-08-01' | 2 | 
    1002 | 200 | '2016-08-01' | 3 | 
    1003 | 100 | '2016-08-02' | 4 | 
    1005 | 100 | '2016-08-02' | 6 | 

我想不出一个ggregate函数可以做我正在寻找的东西,也不会像ANY/EXISTS那样工作。我越来越挂在组织的项目ID ...任何人都可以请指出我在正确的方向吗?

+0

@techspider比'INNER JOIN' –

+1

什么是你的输出逻辑吗?即使项目表中不存在,是否要显示项目2,6行? – techspider

+0

您的预期结果没有意义 - 为什么包含itemid 2和6的行? – Hogan

回答

2

首先,你需要得到复合键,其对应的项目,但包括DISTINCT以避免重复

SELECT DISTINCT extid, extdt 
FROM ents 
JOIN items 
    ON ents.itemid = items.itemid 

现在你检索每一行匹配sele反恐执行局复合键

​​
+0

这样做了! (但我没有看到答案,直到我与其他建议一起工作并开始发布我自己的答案) 首先获取项目中具有itemid的所有extid和extdt组合。然后返回并加入extid和extdt中的ents。 完美。谢谢! – NoTheOtherFry

1
select * 
from ents e1 
where e1.extid in 
    (select extid 
    from ents e2 
    where e2.itemid in (select itemid from items)) 

也许吧?您还可以修改您特定需要的项目ID的最后一个内部查询。

+0

我认为他想要的是,对于他选择的项目id,他想要显示具有匹配extid的所有行。所以可能的方法之一是加入ents表两次(我发布了上面的代码)。 – hchaznedaroglu

+0

这对于让我以不同的方式来看问题非常有帮助。非常感谢。 – NoTheOtherFry

0

从你的描述(而不是例如,这似乎违背它):

SELECT e.* 
FROM item i 
JOIN ent e ON e.itemid = i.itemid 

但我怀疑问题是不是很简单?

1

刚刚加入时间了基于逻辑

SELECT e.* 
-- records from the ents table 
FROM ents e 
-- with an extid that matches 
JOIN ents extid on e.extid = extid.extid 
-- all the records with an itemid in the items table. 
JOIN items i on extid.itemid = i.itemid 

如果唯一键是ID和日期,然后使用

JOIN ents extid on e.extid = extid.extid and e.extdt = extid.extdt 
+0

这对于将问题看作比以前可视化的小块更有用。非常感谢你 – NoTheOtherFry

-1
SELECT e.* 
FROM [Test].[dbo].[ents] e,[Test].[dbo].[items] i 
WHERE e.extid in (SELECT extid from [Test].[dbo].[ents] oe where oe.itemid=i.itemid) 
and e.extdt in (SELECT extdt from [Test].[dbo].[ents] oe where oe.itemid=i.itemid) 
order by itemid 
+1

推广使用'JOIN' sintaxis,Aaron Bertrand写了一篇不错的文章[踢坏坏习惯:使用旧式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/关于它的坏习惯 - 踢 - 使用 - 旧式 - 连接.aspx)。 –