你只需使用group by
和having
select users.user_id, users.name, count(times.time_id) registers
from users
left outer join times
on times.user_id = users.user_id
group by users.user_id, users.name
having count(*) < 2;
例如:
SQL> with users as (select 1 user_id, 'Peter' name from dual union all
2 select 2 user_id, 'kofi' name from dual union all
3 select 3 user_id, 'sam' name from dual union all
4 select 4 user_id, 'nasah' name from dual union all
5 select 5 user_id, 'sarah' name from dual union all
6 select 6 user_id, 'david' name from dual),
7 times as (select 1 time_id, 1 user_id, 'present' register from dual union all
8 select 2 time_id, 2 user_id, 'absent' register from dual union all
9 select 3 time_id, 3 user_id, 'absent' register from dual union all
10 select 4 time_id, 3 user_id, 'absent' register from dual union all
11 select 5 time_id, 4 user_id, 'present' register from dual union all
12 select 6 time_id, 5 user_id, 'absent' register from dual union all
13 select 7 time_id, 5 user_id, 'absent' register from dual)
14 select users.user_id, users.name, count(times.time_id) registers
15 from users
16 left outer join times
17 on times.user_id = users.user_id
18 group by users.user_id, users.name
19 having count(*) < 2;
USER_ID NAME REGISTERS
---------- ----- ----------
6 david 0
1 Peter 1
4 nasah 1
2 kofi 1