ID | user_id | name | active
1 | 1 | Profile 1 | f
2 | 1 | Profile 2 | t
3 | 2 | Profile 3 | f
4 | 2 | Profile 4 | f
5 | 3 | Profile 5 | f
我在用PostgreSQL。在我的应用程序中,
users
可以创建多个profiles
,我想选择每个用户创建的最后一个不同的非活动配置文件。另外,如果有一个active
配置文件属于该用户,它不应该从该用户中选择任何配置文件——这对我来说是困难的部分。为了得到以下结果,我应该使用哪种SQL语句?
4 | 2 | Profile 4 | f
5 | 3 | Profile 5 | f
最佳答案
我会把DISTINCT ON
和NOT EXISTS
结合起来。
假设活动的boolean
类型正确:
SELECT DISTINCT ON (user_id)
id, user_id, name, active
FROM profiles p
WHERE NOT EXISTS (
SELECT 1 FROM profiles
WHERE user_id = p.user_id
AND active -- exclude users with any active profiles
)
ORDER BY user_id, id DESC;
可能是最快最干净的。
关于sql - SQL语句以获取不同的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21636317/