表uzer
:
id | domain_id ---+----------- 10 | 1 11 | 1 12 | 2 13 | 2
表app
:
id| user_id | app_guid | version | created_at --+---------+-----------+---------+------------- 1 | 10 | 7...8 | 100 | 2018-01-18 2 | 11 | 7...8 | 100 | 2018-01-19 3 | 12 | f...4 | 200 | 2018-01-20 4 | 13 | f...4 | 201 | 2018-01-21 5 | 12 | 4...f | 300 | 2018-01-22
unique(user_id, app_guid)
应用程序由它的guid识别 需要选择给定域中的所有唯一应用。
过滤重复项:
version
app_guid
的记录
id
和app_guid
version
的记录
醇>
对于域1,应选择记录1(对于具有最小ID的相同guid和版本选择记录) 对于域2,应选择记录4和5(对于相同的guid选择最新版本)。
Sql fiddle:http://sqlfiddle.com/#!15/3b9d2/1
P.S。请随时更改问题标题以更好地反映问题内容。
答案 0 :(得分:1)
这应该这样做:
SELECT *
FROM
(SELECT app.id,app.user_id,uzer.domain_id,app.app_guid,app.version,app.created_at,
row_number() OVER (PARTITION BY domain_id,app_guid ORDER BY version DESC, app.id) as rank
FROM app,uzer WHERE app.user_id=uzer.id)ranked_app
WHERE rank=1 and ranked_app.domain_id = 1
答案 1 :(得分:1)
规则:
DISTINCT ON (app_guid)
。ORDER BY version DESC, id
查询:
select distinct on (app_guid) *
from app
where exists(select 1 from uzer where uzer.id=app.user_id and uzer.domain_id = 1)
order by app_guid, version desc, id;