为每位患者选择一个约会日期(MySQL)

时间:2015-05-20 18:40:42

标签: mysql sql database

如果我只是为一位病人做这件事:

SELECT * FROM appts where pat_id = 1 and date < '2015-05-20' order by date dsc;

但我需要为每位患者提供这个:

SELECT * FROM appts as a, patients as p where a.pat_id=p.id a.date < '2015-05-20';

但这不起作用,因为它并没有将每位患者的预约数限制为1,并且没有按患者的日期排序。

2 个答案:

答案 0 :(得分:1)

按用户分组并选择最新日期

SELECT pat_id, MAX(date) FROM appts as a WHERE date < '2015-05-20' GROUP BY pat_id;

如果有必要,可以加入患者表。

答案 1 :(得分:0)

使用GROUP BY并使用ORDER BY,而不是排序。另请注意,使用显式连接语法通常被认为是更好的做法,而不仅仅是说“a.pat_id=p.id a.date”。

create table patients  (
  pat_id  numeric,
  pat_name varchar(20)
);

create table appts  (
  pat_id  numeric,
  date date
);

insert into patients values (1,'Anne');
insert into patients values (2,'Bob');
insert into patients values (3,'Chris');
insert into patients values (4,'David');

insert into appts values (1,'2015-01-20');
insert into appts values (1,'2015-05-21');
insert into appts values (2,'2015-03-20');
insert into appts values (2,'2015-04-20');
insert into appts values (3,'2015-05-21');

查询:

select p.pat_id, p.pat_name, max(a.date) as appt_date
from patients p
join appts a
on p.pat_id = a.pat_id
where a.date < '2015-05-20'
group by p.pat_id, p.pat_name
order by appt_date desc;

结果:

pat_id  pat_name    appt_date
2       Bob         April, 20 2015 00:00:00
1       Anne        January, 20 2015 00:00:00