我有表名:目标
id date valueweekmodified goal_type_id user_id
1 2016-01-07 2 1 2016-01-07 16:21:56 3 3
2 2016-01-07 5 1 2016-01-07 16:21:56 1 3
3 2016-01-07 0 1 2016-01-07 17:17:01 3 4
4 2016-01-07 500 1 2016-01-07 17:17:01 1 4
5 2016-01-07 0 1 2016-01-07 17:50:11 3 6
6 2016-01-07 300 1 2016-01-07 17:50:11 1 6
7 2016-01-07 1 1 2016-01-07 17:52:40 3 5
我想获取那些设置了唯一且唯一一个goal_type_id = 3的用户。
例如: 见id 1,2。不应返回该记录,因为user_id = 3有两个goal_type_id = 1和3。
从上表中只有id = 7才有效,因为只有该行包含goal_type_id = 3(对于user_id = 5)。其余的用户设定了两个我不想要的目标。
我该怎么做?
答案 0 :(得分:2)
select user_id from goal
where user_id not in (select user_id from goal where goal_type_id !=3)
and goal_type_id = 3;
整行
select * from goal
where user_id not in (select user_id from goal where goal_type_id !=3)
and goal_type_id = 3;
或
select id, date, value, week,modified, goal_type_id ,user_id
from goal
where user_id not in (select user_id from goal where goal_type_id !=3)
and goal_type_id = 3;
答案 1 :(得分:1)
select user_id
from goal
group by user_id
having bool_and(goal_type_id = 3)
如果所有输入值都为true,则 bool_and
返回 true,否则返回false
https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE