[英]Only return one value for name, SQL Query
I'm trying to find a SQL query that returns stuff in this order我正在尝试查找按此顺序返回内容的 SQL 查询
(Those limits on 99781 and 99780 key it's already by the system, doesn't have to limit on show) (99781和99780键的限制是系统自带的,不必限制显示)
I was using:我正在使用:
SELECT t2.name as name, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0 AND t1.key IN (99781,99780,99777)
ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5
Output: Output:
name![]() |
keyy![]() |
valuee![]() |
---|---|---|
Max![]() |
99781 ![]() |
1 ![]() |
Carl![]() |
99780 ![]() |
1 ![]() |
Max![]() |
99777 ![]() |
402 ![]() |
Carl![]() |
99777 ![]() |
395 ![]() |
Paul![]() |
99777 ![]() |
370 ![]() |
But if name Max have 99781 as 1, and 99777 key as 400. I don't want to return his 99777 key, since he already have 99781 key.但是如果名字 Max 有 99781 作为 1,而 99777 密钥作为 400。我不想归还他的 99777 密钥,因为他已经有 99781 密钥。 Same with Carl (99780 key).
与卡尔(99780 键)相同。
The result I want:我想要的结果:
name![]() |
keyy![]() |
valuee![]() |
---|---|---|
Max![]() |
99781 ![]() |
1 ![]() |
Carl![]() |
99780 ![]() |
1 ![]() |
Paul![]() |
99777 ![]() |
370 ![]() |
Mike![]() |
99777 ![]() |
320 ![]() |
John![]() |
99777 ![]() |
55 ![]() |
A user here on Stack Overflow, helped me get to this: Stack Overflow 上的一位用户帮助我解决了这个问题:
SELECT t2.name as name, t1.key as keyy, t1.value as valuee
FROM player_storage t1 INNER JOIN players t2 on t2.id = t1.player_id
WHERE t1.value > 0
AND
(
t1.key IN (99781, 99780)
OR
(
t1.key IN (99777)
AND NOT EXISTS
(
SELECT 5 FROM player_storage tx
WHERE tx.player_id = t1.player_id
AND tx.key > t1.key
)
)
)
ORDER BY keyy+0 DESC, valuee+0 DESC LIMIT 5
But it's getting only 1 name with 99777 key, even if there are more to show.但它只有 1 个名称和 99777 键,即使还有更多要显示。 It's not going to limit 5, result of this:
它不会限制 5,结果如下:
name![]() |
keyy![]() |
valuee![]() |
---|---|---|
Max![]() |
99781 ![]() |
1 ![]() |
Carl![]() |
99780 ![]() |
1 ![]() |
Paul![]() |
99777 ![]() |
370 ![]() |
You seem to want one row per name, with the rows ordered by key
in descending order.您似乎希望每个名称有一行,行
key
按降序排列。 That would be:那将是:
select ps.*
from (select p.name as name, ps.key as key, p.value as value
row_number() over (partition by name order by key desc) as seqnum
from player_storage ps join
players p
on p.id = ps.player_id
where ps.key in (99781, 99780, 99777)
) ps
where seqnum = 1;
All your values are positive numbers, so I don't understand why there is a condition on positive values.你所有的值都是正数,所以我不明白为什么有正值的条件。 Of course, you can add
and value > 0
to the subquery to enforce this.当然,您可以在子查询中添加
and value > 0
来强制执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.