仅MySQL查询正在选择一个条目

问题描述 投票:0回答:2

我有两个表,h_user和约会,这个查询我想让所有在过去三个月中错过3个以上约会的用户。我正在这样做:

select h_user.name from h_user
  inner join appointment on appointment.id_user=h_user.id
  having count(appointment.missed='y' and date(appointment.datetime)>(curdate()-interval 3 month))>3;

我的问题是,当我运行此程序时,由于包含了这些用户,我只能得到一个用户,而我应该得到两个用户(第三个值在这里不相关,这是医生的ID):

insert into appointment values('2019-10-11 16:00:00','1','10','y');
insert into appointment values('2019-11-15 10:00:00','1','11','y');
insert into appointment values('2019-12-14 10:00:00','1','11','y');
insert into appointment values('2019-11-21 10:00:00','1','11','y');
insert into appointment values('2019-10-21 10:00:00','1','11','y');
insert into appointment values('2019-10-11 16:00:00','2','12','y');
insert into appointment values('2019-11-15 10:00:00','2','13','y');
insert into appointment values('2019-12-14 10:00:00','2','13','y');
insert into appointment values('2019-11-21 10:00:00','2','13','y');
insert into appointment values('2019-10-21 10:00:00','2','13','y');

另外,当我删除用户时,结果给了我并再次运行,它给了我另一个,所以我知道它仅对一个用户有效。如果有人可以帮助我解决这个大问题,请提前联系!

mysql database select count having
2个回答
2
投票

很容易,您的查询缺少group by子句(MySQL的旧版本允许),因此它给您错误的结果。只需添加缺少的子句(您想在group by中包含users表的主键列,以防两个不同的用户具有相同的name)。

您应将所有条件移至where子句以提高效率。我还建议不要对表列使用date(),因为这样会破坏现有索引;没有此功能,您可以获得相同的结果。

考虑:

select u.name 
from h_user u
inner join appointment a  on a.id_user = u.id
where a.datetime > curdate() - interval 3 month and a.missed = 'y'
group by u.id, u.name 
having count(*) > 3;

Demo on DB Fiddle

|名称|| :--- || foo ||酒吧

1
投票

您缺少group by h_user.name子句,还应该在WHERE子句中移动第二个条件:

select h_user.name 
from h_user inner join appointment on 
appointment.id_user=h_user.id
where date(appointment.datetime)>(curdate()-interval 3 month) 
group by h_user.name
having sum(appointment.missed='y')>3

请注意,在group by子句中使用用户ID更为安全,以避免2个或更多用户具有相同名称的情况。所以这会更好:

select h_user.id, h_user.name 
.................................
group by h_user.id, h_user.name
.................................
© www.soinside.com 2019 - 2024. All rights reserved.