从多个选项中从数据库中获取唯一记录
Fetch unique record from database from multiple option
我有 table 名字:目标
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.
例如:
见编号 1,2。不应返回该记录,因为 user_id=3 有两个 goal_type_id=1 和 3.
从上面的 table 来看,只有 id=7 是有效的,因为只有该行包含 goal_type_id = 3(对于 user_id=5)。其余所有用户设置了两个我不想要的目标。
我该怎么做?
select user_id
from goal
group by user_id
having bool_and(goal_type_id = 3)
bool_and
returns 如果所有输入值都为真则为真,否则为假
https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE
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;
我有 table 名字:目标
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.
例如: 见编号 1,2。不应返回该记录,因为 user_id=3 有两个 goal_type_id=1 和 3.
从上面的 table 来看,只有 id=7 是有效的,因为只有该行包含 goal_type_id = 3(对于 user_id=5)。其余所有用户设置了两个我不想要的目标。
我该怎么做?
select user_id
from goal
group by user_id
having bool_and(goal_type_id = 3)
bool_and
returns 如果所有输入值都为真则为真,否则为假
https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE
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;