如何从具有相同 ID 的帖子中获取最低值
How to get lowest value from posts with the same ID
我的样本table:
ID | Post_id | Score
1 | 1 | 33
2 | 1 | 43
3 | 1 | 27
4 | 1 | 66
我想获取具有最低值(分数)的行。在这种情况下是:
ID | Post_id | Score
3 | 1 | 27
我的查询:
SELECT * FROM table WHERE post_id = '1' GROUP BY post_id ORDER BY Score ASC
但这不起作用,因为它 returns 我:得分:33
如何解决?如果我有数千行并且希望 post_id 对于最低值是唯一的怎么办?
对于单个 id
,只需删除 group by
并使用 limit
:
SELECT *
FROM table
WHERE post_id = 1
ORDER BY Score ASC
LIMIT 1;
我假设 post_id
是一个数字。将数字与数字进行比较,而不是与字符串进行比较。
编辑:
如果你想要这个 per post_id,那么只需使用相关子查询:
select t.*
from t
where t.score = (select min(t2.score) from t t2 where t2.post_id = t.post_id);
如果您可能有多行得分最低,您可以使用 sub-query :
SELECT *
FROM test
WHERE post_id = 1
AND score = (
SELECT MIN(score)
FROM test
WHERE post_id = 1
)
Fiddle : https://www.db-fiddle.com/f/3ppntnA77HFpKRU82h32Gv/1
下面应该可以解决问题:
Select
id,
score,
Post_id,
min(score)
from
table
where
score = min(score);
您必须使用子查询为每个 post_id
选择最小值。
SELECT a.* FROM records a
JOIN
( SELECT post_id, MIN(score) as min_score
FROM records GROUP BY post_id
) b
ON a.score=b.min_score;
输出
| id | post_id | score |
| --- | ------- | ----- |
| 3 | 1 | 27 |
| 5 | 2 | 20 |
如果您使用的是 MySQL v8.0,则可以使用 ROW_NUMBER()
函数对结果进行排序。这样您就可以选择分数较低的行,然后 return 从中选择所有内容:
select
sq.id, sq.post_id, sq.score
from
(select id, post_id, score
, row_number() over (partition by post_id order by score) RowNo
from test) sq
where sq.RowNo = 1
这里有一个Fiddle来测试代码:https://www.db-fiddle.com/#&togetherjs=8dHSCs50Iq
我还在您的示例数据旁边添加了另一个 post_id,以演示它如何对多个 post_id 的
做出反应
我的样本table:
ID | Post_id | Score
1 | 1 | 33
2 | 1 | 43
3 | 1 | 27
4 | 1 | 66
我想获取具有最低值(分数)的行。在这种情况下是:
ID | Post_id | Score
3 | 1 | 27
我的查询:
SELECT * FROM table WHERE post_id = '1' GROUP BY post_id ORDER BY Score ASC
但这不起作用,因为它 returns 我:得分:33
如何解决?如果我有数千行并且希望 post_id 对于最低值是唯一的怎么办?
对于单个 id
,只需删除 group by
并使用 limit
:
SELECT *
FROM table
WHERE post_id = 1
ORDER BY Score ASC
LIMIT 1;
我假设 post_id
是一个数字。将数字与数字进行比较,而不是与字符串进行比较。
编辑:
如果你想要这个 per post_id,那么只需使用相关子查询:
select t.*
from t
where t.score = (select min(t2.score) from t t2 where t2.post_id = t.post_id);
如果您可能有多行得分最低,您可以使用 sub-query :
SELECT *
FROM test
WHERE post_id = 1
AND score = (
SELECT MIN(score)
FROM test
WHERE post_id = 1
)
Fiddle : https://www.db-fiddle.com/f/3ppntnA77HFpKRU82h32Gv/1
下面应该可以解决问题:
Select
id,
score,
Post_id,
min(score)
from
table
where
score = min(score);
您必须使用子查询为每个 post_id
选择最小值。
SELECT a.* FROM records a
JOIN
( SELECT post_id, MIN(score) as min_score
FROM records GROUP BY post_id
) b
ON a.score=b.min_score;
输出
| id | post_id | score |
| --- | ------- | ----- |
| 3 | 1 | 27 |
| 5 | 2 | 20 |
如果您使用的是 MySQL v8.0,则可以使用 ROW_NUMBER()
函数对结果进行排序。这样您就可以选择分数较低的行,然后 return 从中选择所有内容:
select
sq.id, sq.post_id, sq.score
from
(select id, post_id, score
, row_number() over (partition by post_id order by score) RowNo
from test) sq
where sq.RowNo = 1
这里有一个Fiddle来测试代码:https://www.db-fiddle.com/#&togetherjs=8dHSCs50Iq
我还在您的示例数据旁边添加了另一个 post_id,以演示它如何对多个 post_id 的
做出反应