2017-08-29 53 views
0

我想進行查詢以選擇用戶未註冊的所有研討會信息。我想用1個查詢獲得所有數據。查詢選擇用戶未註冊的所有研討會

這就是:車間表 The workshops table 的:登記表 ​​ 的:workshop_rounds表 The workshop_rounds table

希望你們有些人能幫助我。 在此先感謝!

我試過這個查詢,但它不是我想要的,它很接近但並不完全。

SELECT * FROM `workshop_rounds` WHERE `id` != ALL (SELECT `workshop_round_id` FROM `registrations` WHERE `user_id` = 1) AND `workshop_id` != ALL (SELECT `workshop_id` FROM `workshop_rounds` WHERE `workshop_id`= ALL (SELECT `workshop_round_id` FROM `registrations` WHERE `user_id` = 1)) 

結果是: enter image description here

但現在我也想不相同workshop_id的用戶被註冊輪得到其他回合。希望你能理解我。

+0

到目前爲止您嘗試過哪些方法?您卡在哪裏? – Jens

+0

我試過這個 –

+0

見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very -simple-sql-query – Strawberry

回答

1

使用NOT EXISTS

SELECT * 
FROM workshops w 
WHERE NOT EXISTS 
(
    SELECT 1 
    FROM registrations r 
    JOIN "workshop_rounds" wr ON r."workshop_round_id" = wr.id 
    WHERE wr.workshop_id = w.id 
      AND r."user_id" = 1 
); 

,也許更簡潔NOT IN

SELECT * 
FROM workshops w 
WHERE w.id NOT IN 
(
    SELECT wr.workshop_id 
    FROM registrations r 
    JOIN "workshop_rounds" wr ON r."workshop_round_id" = wr.id 
    WHERE r."user_id" = 1 
); 
1

對於單個用戶,我會not exists接近這一點:

select w.* 
from workshops w 
where not exists (select 1 
        from registrations r 
        where r.workshop_id = w.id and 
         r.user_id = THE USER ID 
       ); 
+0

這是不是我想回來,謝謝你的嘗試壽 –

0


試試這個去取所有用戶的研討會未註冊

select ws.* from workshops ws 
     where ws.id not in (select w.id from workshops w, workshop_rounds wr, registrations r 
       where r.workshop_round_id = wr.id and wr.workshop_id=w.id and r.user_id = THE_USER_ID);