我有一个包含表格的医院数据库:
equipment
id CHAR(40) NOT NULL,
model CHAR(20) NOT NULL,
serialno VARCHAR(20) NOT NULL,
release_date DATE,
PRIMARY KEY (id)
和
appointmentrelations
appointment_id CHAR(40) NOT NULL,
medicine_id CHAR(40) NOT NULL,
equipment_id CHAR(40) NOT NULL,
PRIMARY KEY (appointment_id, medicine_id, equipment_id),
FOREIGN KEY (appointment_id) REFERENCES appointment(id),
FOREIGN KEY (medicine_id)REFERENCES medicineprice(medicine_id),
FOREIGN KEY (equipment_id) REFERENCES equipment(id)
和其他一些表格。
表约定描述了医院的预约,并将设备与其中使用的药物相关联。
我想写一个查询,找出与他的年龄相关的最多使用的设备。
appointmentrelations
a1 m1 e1
a2 m2 e2
a3 m3 e3
a4 m3 e3
a5 m4 e2
equipment
e1 model1 se1 2004-07-14
e2 model2 se2 2017-10-19
e3 model3 se3 2015-01-08
在上面的样本中,与他的年龄相关的使用最多的设备是e2。
我尝试了以下内容:
SELECT equipment_id, COUNT(DISTINCT appointment_id) AS ab
FROM appointmentrelations
GROUP BY equipment_id
ORDER BY ab DESC
LIMIT 1
计算每台设备的使用次数,但我不知道如何将其与设备年龄联系起来。
答案 0 :(得分:1)
If i understand correctly, you can wrap your current query in subquery
:
SELECT *
FROM equipment e
WHERE id = (SELECT equipment_id
FROM appointmentrelations
GROUP BY equipment_id
ORDER BY COUNT(DISTINCT appointment_id) DESC
LIMIT 1);
答案 1 :(得分:0)
您可以使用内部联接来按使用情况获取所有结果顺序
select e.id, count(DISTINCT a.appointment_id), e.model, e.date
from equipment e
inner join appointmentrelations a on a.appointment_id = e.id
group by e.id , e.model, e.date
order by count(DISTINCT a.appointment_id) DESC