2017-03-16 122 views
0

我有以下表格:在SQL查詢一個一對多的具有條件關係

event_tbl

| event_id (PK) | event_date | event_location | 
|---------------|------------|----------------| 
| 1    | 01/01/2018 | Miami   |     
| 2    | 02/04/2018 | Tampa   |      

performer_tbl

| performer_id (PK) | event_id (FK) | genre | 
|-------------------|---------------|-------| 
| 1     | 1    | A | 
| 2     | 1    | B | 
| 3     | 2    | A | 
| 4     | 2    | C | 

我想找到有兩種類型的事件A和流派B(應該只是返回事件1),並且在寫查詢時我迷失了方向。也許我只是沒有足夠的咖啡,但我所能想到的是做兩個帶有case語句的派生列,該語句通過event_id計算流派和組,然後將兩者過濾爲> 0。它看起來不太優雅。

+1

哪些DBMS您使用的? Postgres的?甲骨文? –

回答

0

如果您正在使用SQL Server,以下檢查:

Select * From 
    event_tbl 
    where event_id 
    IN 
    (
    select event_id 
    from performer_tbl as A 
    where exists (select 1 
       from perfoermer_tbl as B 
       where B.event_id = A.event_id and B.genre = 'A') 
     and 
     exists (select 1 
       from perfoermer_tbl as B 
       where B.event_id = A.event_id and B.genre = 'B') 
) 
0

這應該做的工作(在MySQL,其他DBMS的語法可以很容易地改變):

SELECT 
e.event_id 
FROM 
event_tbl e 
JOIN performer_tbl p USING(event_id) 
GROUP BY e.event_id 
HAVING SUM(IF(p.genre = 'A', 1, 0)) >= 1 AND SUM(IF(p.genre = 'B', 1, 0)) >= 1; 
1

這應該在任何SQL數據庫中工作(至少在mysql,sql server,postgres或oracle)

select event_tbl.* FROM (
    select event_id 
    from performer_tbl 
    where genre = 'A' 
    GROUP BY event_id) a_t 
    INNER JOIN (select event_id 
    from performer_tbl 
    where genre = 'B' 
    GROUP BY event_id) b_t 
    ON a_t.event_id = b_t.event_id 
    INNER JOIN event_tbl 
    ON event_tbl.event_id = a_t.event_id 
0

這也適用於使用左連接s :(由於沒有函數調用或子選擇,所以速度很快。此外,它在大多數SQL引擎可用)

SELECT DISTINCT 
    p1.event_id 
    ,e.event_date 
    ,e.event_location 
FROM 
    performer_tbl as p1 
    inner join event_tbl as e on 
     p1.event_id = e.event_id 
    left outer join performer_tbl as p2 on 
     p1.event_id = p2.event_id 
     AND p2.genre = 'A' 
    left outer join performer_tbl as p3 on 
     p1.event_id = p3.event_id 
     AND p3.genre = 'B' 
WHERE 
    p2.genre IS NOT NULL 
    AND p3.genre IS NOT NULL; 
0

如果我理解正確,你需要什麼,你可以試試這個:

Select * 
    from event_tbl e 
where exists (select * 
       from performer_tbl p 
       where p.event_id = e.event_id 
        and p.genre in ('A', 'B'))