SQL查询,列出x具有> 1 z的所有x

时间:2017-11-09 23:24:56

标签: sql postgresql

这是我的模特

enter image description here

假设一切都已正确实现,我需要做的是查询在多​​个校园中有课程的模块。换句话说“查找在多个校园中有课程的模块列表”

SELECT module_id FROM (
    SELECT * FROM (
        SELECT * FROM (
            SELECT module_id, room FROM timetable
        )a JOIN (SELECT building, room FROM rooms)b USING (room)
    )c JOIN (SELECT campus, building FROM buildings)d USING (building) 
)e GROUP BY module_id,campus HAVING COUNT(campus) > 1; 

这就是我所拥有的,但它没有做我想要的事情

1 个答案:

答案 0 :(得分:0)

你有方式太多嵌套查询!

您只需要一个简单的查询,正确连接所有表,然后将组放在其上,然后放在上面。这里没有理由使用嵌套查询,查询看起来像

select [columns you want to return]
from timetable
join module on [...]
join room on [...]
join building on [...]
group by [columns you want to return]
having count(*) > 1;

祝你好好完成其余的功课!