Select 多个表只有唯一用户并按最新 ID 排序
Select multiple tables with only unique users and ordered by latest id
我有 2 个表,第一个叫做 members:
id name show
1 John 1
2 Wil 1
3 George 1
4 Chris 1
第二个叫分数:
id user_id score
1 1 90
2 1 70
3 2 55
4 3 30
5 3 40
6 3 100
7 4 30
user_id from score 是成员的id。
我想要的是显示一个具有独特 members.id 的得分列表,按 score.score 排序并按最新的 score.id.
排序
我使用以下代码:
SELECT members.id, members.show, score.id, score.user_id, score.score FROM members
INNER JOIN score ON score.user_id = members.id
WHERE members.show = '1'
GROUP BY score.user_id
ORDER BY score.score DESC, score.id DESC
输出未按最新的 score.id 排序,但确实仅显示唯一的 user_id:
id user_id score
1 1 90
3 2 55
4 3 30
7 4 30
应该是这样的:
id user_id score
6 3 100
2 1 70
3 2 55
7 4 30
希望你能帮帮我
您可以使用:
with cte as (
select id,
user_id,
score,
row_number() over(partition by user_id order by id desc) as row_num
from score
) select cte.id,user_id,score
from cte
inner join members m on cte.user_id=m.id
where row_num=1
order by score desc;
如果您的 MySQL
服务器不支持 windows 功能,请使用:
select s.id,s.user_id,s.score
from score s
inner join members m on s.user_id=m.id
where s.id in (select max(id) as id
from score
group by user_id
)
order by score desc;
我有 2 个表,第一个叫做 members:
id name show
1 John 1
2 Wil 1
3 George 1
4 Chris 1
第二个叫分数:
id user_id score
1 1 90
2 1 70
3 2 55
4 3 30
5 3 40
6 3 100
7 4 30
user_id from score 是成员的id。 我想要的是显示一个具有独特 members.id 的得分列表,按 score.score 排序并按最新的 score.id.
排序我使用以下代码:
SELECT members.id, members.show, score.id, score.user_id, score.score FROM members
INNER JOIN score ON score.user_id = members.id
WHERE members.show = '1'
GROUP BY score.user_id
ORDER BY score.score DESC, score.id DESC
输出未按最新的 score.id 排序,但确实仅显示唯一的 user_id:
id user_id score
1 1 90
3 2 55
4 3 30
7 4 30
应该是这样的:
id user_id score
6 3 100
2 1 70
3 2 55
7 4 30
希望你能帮帮我
您可以使用:
with cte as (
select id,
user_id,
score,
row_number() over(partition by user_id order by id desc) as row_num
from score
) select cte.id,user_id,score
from cte
inner join members m on cte.user_id=m.id
where row_num=1
order by score desc;
如果您的 MySQL
服务器不支持 windows 功能,请使用:
select s.id,s.user_id,s.score
from score s
inner join members m on s.user_id=m.id
where s.id in (select max(id) as id
from score
group by user_id
)
order by score desc;