sql过滤多对多的关系

时间:2012-12-07 07:06:28

标签: sql sql-server

我有以下表格

competitions
id prize
1 win a car
2 win an ipod

competition_type
competition_id Type_id
  1              1
  1              2
  2              1

Type
id   type
1    facebook
2    twitter

我如何选择所有比赛,而不是推特。所以我应该赢得一个ipod作为最终结果?

5 个答案:

答案 0 :(得分:1)

查询怎么样:

Select Prize from 
Competitions a inner join competition_type b on a.id=b.competition_id
    inner join Type c on b.Type_id=c.id
Where c.Type='facebook' and c.Type<>'twitter'

答案 1 :(得分:1)

SELECT
    ct.competition_id FROM
    competitions c
JOIN competition_type ct ON ct.competition_id = c.id AND ct.Type_id = 1 
WHERE
    NOT EXISTS(SELECT * FROM competitions c2 
                     JOIN competition_type ct2 
                     ON ct2.competition_id = c2.id AND ct2.Type_id = 2 
                     WHERE c2.id = c.id)

答案 2 :(得分:1)

试试这个 -

select cmp.id, cmp.prize from 
competitions cmp inner join competition_type ct on cmp.id = ct.competition_id
inner join Type t on t.id = ct.type_id
where t.type = 'facebook'

答案 3 :(得分:1)

SELECT  a.*
FROM    competition a
WHERE   a.id NOT IN
(
    SELECT  b.competition_id
    FROM    competition_type b 
            INNER JOIN Type c
                ON b.type_ID = c.id
    WHERE   c.type = 'twitter'
)

答案 4 :(得分:1)

请看一下这个例子

select * from Competitions as c
left join competition_type as ct
on c.id = ct.competition_id
left join Type as t
on t.id = ct.Type_id
where t.Type <> 'Twitter'
;

结果:

ID  PRIZE         COMPETITION_ID    TYPE_ID     TYPE
1   win a car     1                 1           facebook
2   win an ipod   2                 1           facebook

**已更新为&lt;&gt; Twitter

SQLFIDDLE Reference