0

我的目标是访问我的数据库并获得两件事:

1st - 每个教室有多少台电脑:

select 
    room.idRoom, count(*) as 'Existing Computers'
from
    room,
    computer
where
    room.idRoom = computer.idRoom
group by room.idRoom

2nd - 正在使用多少台计算机:

select 
    room.idRoom,
    count(*) as 'Computers Used'
from
    room,
    session,
    computer
where
    room.idRoom = computer.idRoom
        and computer.idComputer = session.idComputer
        and session.logout is null
group by room.idRoom

尽管这两个查询可以分开工作,但我希望我的结果表只显示数量'Existing Computers'等于数量的房间'Computers Used'。主要目标是有一个完整的房间列表。最好以这种方式:

idRoom | Existing Computers | Computers Used 
B100   |      4             |        4
B101   |      10            |        10

很抱歉没有为这个问题使用正确的格式,但我是 stackoverflow 的新手,我没有多少时间来解决这个问题,因为我的项目将于本周日到期。提前谢谢你的帮助 :)

4

3 回答 3

0

所以加入他们:

Select t1.idRoom, t1.ExistingComputers, t2.UsedComputers
    (select 
        room.idRoom, count(*) as ExistingComputers
    from  
        room,
        computer  
    where
        room.idRoom = computer.idRoom
    group by room.idRoom) t1
inner join 
    (select 
        room.idRoom,
        count(*) as UsedComputers
    from
        room,
        session,
        computer
    where
        room.idRoom = computer.idRoom
            and computer.idComputer = session.idComputer
            and session.logout is null
    group by room.idRoom) t2 on t1.idRoom = t2.idRoom

我保持你的伪代码不变。基本思想是,您为您选择的第一个表指定一个别名,为您选择的第二个表指定一个别名,然后将它们加入 idRoom。

于 2013-06-14T17:47:22.447 回答
0

试试这个

Select ext.idRoom,
    ExistingComputers as 'Existing Computers',
    ComputersUsed as 'Computers Used'
from
    (select 
        room.idRoom, count(*) as ExistingComputers
    from
        room,
        computer
    where
        room.idRoom = computer.idRoom
    group by room.idRoom) as ext
inner join
    (select 
        room.idRoom,
        count(*) as ComputersUsed
    from
        room,
        session,
        computer
    where
        room.idRoom = computer.idRoom
            and computer.idComputer = session.idComputer
            and session.logout is null
    group by room.idRoom) as usd
on ext.idRoom = usd.idRoom
and ext.ExistingComputers = usd.ComputersUsed

干杯

于 2013-06-14T17:49:42.767 回答
0

您可以在一个查询中执行此操作,无需子查询。

如果您将计算机加入注销为 NULL 的会话,那么您只会得到

SELECT r.idRoom, COUNT(*) AS 'Existing Computers In Use'
FROM room AS r
JOIN computer AS c ON r.idRoom=c.idRoom
JOIN session AS s ON c.idComputer=s.idComputer 
WHERE s.logout IS NULL
GROUP BY r.idRoom

值得使用 SQL-92JOIN语法。

于 2013-06-14T17:51:23.863 回答