MySQL查询丢失的ID

时间:2015-04-08 18:29:48

标签: mysql sql

我有三张桌子,我想查询哪些人缺席(事件中缺失,即特定事件的出勤表中缺少idu),以及他们缺席了多少次在某个日期范围内。例如,如果事件发生5次并且用户转到其中一个,我想要显示用户错过了四个事件。  我还想将个人可以缺席的次数设置为缺席列表中的最少次数为3.因此查询将向我显示错过事件超过3次的用户。我的表格如下所示

用户表

idu     fname   lname
1       John    Doe
2       Jane    Doe
3       Mary    Jane
4       John    Rancho

活动表

id_event    event_name
1           Conference
2           Fellowship
3           Orientation

活动考勤表

id_attendance   id_event    idu event_date
1               1           1   2012-02-01 08:00:00
2               1           2   2012-02-01 08:00:00
3               2           1   2012-06-07 08:00:00
4               2           3   2012-06-07 08:00:00
5               3           1   2013-07-12 08:00:00
6               3           2   2013-07-12 08:00:00
7               1           1   2014-05-31 08:00:00
8               1           3   2014-05-31 08:00:00
9               2           1   2015-02-08 08:00:00

我希望结果显示如下,其中第一列是idu 因此结果将如此

IDU  Name      Times Absent
2   Jane Doe    3
3   Mary Jane   4

我的查询如下所示。我被卡住了。

SELECT idu 
FROM users 
WHERE idu NOT IN (
         SELECT idu 
         FROM events 
         LEFT JOIN attendance 
         ON event_id=id_event
         WHERE event_date>='2011-04-08 00:00:00' 
         AND event_date<='2019-04-08 00:00:00'
         AND id_event IN(11,10) AND idu IS NOT NULL)

2 个答案:

答案 0 :(得分:1)

SELECT 
    ut.idu as IDU,
    ut.fname || ut.lname as Name,
    (SELECT COUNT(*) FROM events_table) - SUM(CASE WHEN at.idu is null then 0 else 1 end) as TimesAbsent
FROM attendance_table at
RIGHT JOIN user_table ut
ON at.idu = ut.idu
GROUP BY ut.idu, ut.fname, ut.lname

答案 1 :(得分:0)

我认为,您希望获得的用户数量超过或等于四次。

请使用以下查询。

select
*
from
(select
u.idu as IDU,concat(u.fname,' ', u.lname) as Name,
(CASE
WHEN a.idu IS NULL THEN (SELECT  count(distinct id_event,event_date) FROM attendance)
ELSE ((SELECT  count(distinct id_event,event_date) FROM attendance) - count(*))
END) as Number_of_Absent
from users u
left join attendance a on (a.idu=u.idu)
group by concat(u.fname,' ', u.lname) order by Number_of_Absent) a where Number_of_Absent >=4 ;

您可以看到查询结果,请点击.. SQL fiddle

如果您想查看所有用户不在,请尝试以下查询。

select
u.idu as IDU, concat(u.fname,' ', u.lname) as Name,
(CASE
WHEN a.idu IS NULL THEN (SELECT  count(distinct id_event,event_date) FROM attendance)
ELSE ((SELECT  count(distinct id_event,event_date) FROM attendance) - count(*))
END) as Number_of_Absent
from users u
left join attendance a on (a.idu=u.idu)
group by concat(u.fname,' ', u.lname) order by Number_of_Absent

您可以看到查询结果,请点击.. SQL fiddle

根据上表,用户缺席列表后的数据

enter image description here