1

假设我有两张桌子,patients并且rooms,并且patients

CREATE TABLE patient (
    id int,
  room int,
  FOREIGN KEY (room) REFERENCES room (id)
);

并且room

CREATE TABLE rooms (
    id int,
);

我想创建一个视图,rooms其中包括那个房间里有多少病人。我可以计算房间里的病人数量

select count(1) from patients where room = N;

对于任何现有的房间N。我将如何写SELECT我需要的语句?


我最好的解决方案:

select *,
       count(1) as patients_in_room
                from patients
                where patients.room = rooms.id
       from rooms;
4

3 回答 3

3

这将带来所有房间,patientsCount = 0当它们是空的。

SELECT r.id roomId, coalesce(count(p.room),0) patientsCount
FROM room r left join patients p on r.id = p.room
GROUP BY r.id
于 2013-10-17T21:17:51.563 回答
1
SELECT room, COUNT(*) patients_in_room
FROM patient
GROUP BY room
于 2013-10-17T21:13:47.987 回答
1

您可以使用 MySQL 聚合函数,请参阅文档

对于您上面提出的问题,您可以使用以下查询:

SELECT room, COUNT(*) FROM patient GROUP BY room

干杯!!

于 2013-10-17T21:18:45.803 回答