MySQL 仅查询是选择一个条目

MySQL query only is selecting one entry

我有两个表,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');

此外,当我删除用户时,结果又给了我 运行,它给了我另一个,所以我知道它只对一个用户有效。如果有人能帮我解决这个问题那就太好了,提前联系!

您缺少 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
.................................

基本上您的查询缺少 group by 子句(旧版本的 MySQL 允许),因此它给您错误的结果。只需添加缺少的子句(您确实希望在 group by 中包含用户 table 的主键列,以防两个不同的用户具有相同的 name)。

您应该将所有条件移至where子句以提高效率。我还建议不要对 table 列使用 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:

| name |
| :--- |
| foo  |
| bar  |