加入两张桌子

时间:2011-10-03 19:59:24

标签: sql join

我是新手,加入两张桌子时遇到了一些麻烦。 table1:(topicID,questionID)其中topicID是主键。对于每个topicID,都有很多questionID。

现在,我有一个带有questioID的table2,我想从table1获取所有那些topicID,其中table2中的每个questionID至少有一个条目。

我将不胜感激。

create table table1(
    topicID int,
    questionid int)
create table table2
(
    questionid int
)
insert into table1
select 1,1
union all
select 2,1
union all
select 2,2
union all
select 2,4
union all
select 1,2
union all
select 1,6

insert into table2 
select 1
union all
select 2
union all
select 6

使用上面的table1和table2,查询应该将topicID返回为2,因为只有这个对于table2中的每个questionID至少有一个条目。

由于

2 个答案:

答案 0 :(得分:4)

SELECT topicID
    FROM table1
    GROUP BY topicID
    HAVING COUNT(DISTINCT questionid) = (SELECT COUNT(*) FROM table2)

答案 1 :(得分:0)

您需要的关系运算符是division,通常称为"the supplier who supplies all parts"

因为您的规范声明“每个questionID至少有一个条目”,我认为您应该关注division with remainder

P.S。这不是几乎所有SQL引用的第1页上都会找到的主题,而是它是一个比较模糊的关系运算符!

相关问题