簡體   English   中英

sql過濾器多對多關系

[英]sql filter many to many relationship

我有下表

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 ipod作為最終結果?

查詢如何:

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'
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)

嘗試這個 -

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'
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'
)

請看這個例子

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參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM