0

我有以下表格

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

我怎样才能选择所有是 facebook 但不是 twitter 的比赛。所以我应该得到 Win an ipod 作为最终结果?

4

5 回答 5

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'
于 2012-12-07T07:09:27.663 回答
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)
于 2012-12-07T07:11:43.880 回答
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'
于 2012-12-07T07:11:52.670 回答
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'
)
于 2012-12-07T07:13:15.597 回答
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

** 更新为 <> Twitter

SQLFIDDLE 参考

于 2012-12-07T07:16:05.740 回答