从 MySQL 中的表的一部分中选择最小值和最大值

发布于 2024-10-17 07:38:26 字数 388 浏览 2 评论 0原文

如果我想从整个表中选择最小值和最大值,我可以使用这个:

SELECT min(price) as min_price, max(price) as max_price FROM `prices`

但是如何从表的一部分中选择最小值和最大值? 例如,我的表中有 30 行。我想从前十行中选择最小值和最大值,然后从后十行中选择最小值和最大值,然后形成最后 10 行。

我尝试过类似的操作,

SELECT min(price) as min_price, max(price) as max_price FROM `prices` LIMIT 0,10

但这不起作用。

如何用最少的查询来解决这个问题?

If I want to select min and max values from a whole table I can use this:

SELECT min(price) as min_price, max(price) as max_price FROM `prices`

But how to select min and max values from just a part of a table?
For example, I have 30 rows in a table. I want to select min and max values from first ten rows, then from second ten rows and then form the last 10.

I've tried something like

SELECT min(price) as min_price, max(price) as max_price FROM `prices` LIMIT 0,10

but this did not work.

How can I solve this problem with minimum queries?

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

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

发布评论

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

评论(2

注定孤独终老 2024-10-24 07:38:26
SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice FROM (SELECT PRICE FROM PRICES LIMIT 10) tmp;

此外,MySQL 有一个很酷的功能,可以让您返回任意范围的行(例如返回行 10-20)。这对于显示记录页非常方便:

SELECT column FROM table
LIMIT 10 OFFSET 20

上面的查询将返回第 20-30 行。

简而言之,要在查询中返回 20 到 30 行,您可以使用:

SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice 
FROM (SELECT PRICE FROM PRICES LIMIT 10 OFFSET 20);

您需要更改偏移值以指定范围的起点。

SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice FROM (SELECT PRICE FROM PRICES LIMIT 10) tmp;

moreover, MySQL have a cool feature that will let you return an arbitrary range of rows (eg return rows 10-20). This is very handy for displaying pages of records:

SELECT column FROM table
LIMIT 10 OFFSET 20

The above query will return rows 20-30.

So in short, to return rows from 20 to 30 in case of your query, you use:

SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice 
FROM (SELECT PRICE FROM PRICES LIMIT 10 OFFSET 20);

YOU need to change the offset value to specify the start point of your range.

唱一曲作罢 2024-10-24 07:38:26

你有没有尝试过:

SELECT min(price) as min_price, max(price) as max_price FROM 
    (SELECT price FROM `prices` LIMIT 0,10);

Have you tried :

SELECT min(price) as min_price, max(price) as max_price FROM 
    (SELECT price FROM `prices` LIMIT 0,10);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文