MySQL 选择范围之间的 n 行

发布于 2024-12-23 14:38:34 字数 381 浏览 3 评论 0原文

假设我有一个如下所示的表:

ID| Value
1 | 98
2 | 56
3 | 37
4 | 100
5 | 96
6 | 23

...我只想选择四行。但是,行需要代表集合(它将显示为折线图),所以在这种情况下,我想要这样的东西:

ID| Value
1 | 98
2 | 56
4 | 100
6 | 23

即,最多 n 的范围(在本例中为四个)结果,包括最小值和最大值,每个结果与其余结果的“间隔”尽可能相等。

我对 MySQL 的要求是否过高,如果是这样,您会推荐哪些其他方法?我非常希望避免选择每一行,然后使用 PHP 过滤掉一些行。

非常感谢

费拉

Say I have a table that looks like this:

ID| Value
1 | 98
2 | 56
3 | 37
4 | 100
5 | 96
6 | 23

...and I only want to select four rows. However, the rows need to be representative of the set (it will be displayed as a line graph), and so I want, in this case, something like this:

ID| Value
1 | 98
2 | 56
4 | 100
6 | 23

Ie., a range of at most n (in this case four) results, including the minimum and maximum, with each result "spaced" as equally as possible from the rest.

Is what I'm asking for too much for MySQL, and if so, which other means would you recommend? I'd very much like to avoid selecting every single row, and then filtering some out using PHP.

Thanks a lot

Fela

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔女人霸气范 2024-12-30 14:38:34

这是可能的,但你不想这样做。

您可以提取最小值 (SELECT MIN()) 和最大值 (SELECT MAX()),您可以确定一组中有多少个结果 (SELECT COUNT())。通过计数,您可以选择结果集中的特定行 (SELECT ... LIMIT 2,1)。然后你可以将所有这些UNION放在一起。但这将是一个非常可怕的 SQL 语句,而且它真的不是你想要使用 SQL 的东西。

更好的是,您提取所有有问题的结果(可能是适当排序的),并在不同级别过滤您的结果。

It's possible, but you don't want to do it.

You can pull the minimum (SELECT MIN()) and the maximum (SELECT MAX()), you can determine how many results are in a set (SELECT COUNT()). With the count, you can select specific rows in the result set (SELECT ... LIMIT 2,1). And then you could UNION all of these together. But it's going to be a pretty horrendous SQL statement, and it's really, really, not something that you want to use SQL for.

Far better that you pull all the results in question, perhaps ordered appropriately, and filter your results at a different level.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文