MYSQL - 限制在一个范围内

发布于 2024-11-15 11:08:00 字数 1093 浏览 2 评论 0原文

我已经使用 AJAX 构建了一个滑块来获取结果,但我遇到了一个小问题,如下所示:

假设一个表包含一组 1 到 15 行,但是,我只处理前 9 行行;在第一阶段 i (SELECT * FROM table ORDER BY id DESC LIMIT 9) 并使用结果构建导航并显示第一组。

然后在第二阶段我正在查询这9个项目,每次从左侧开始查询3个,所以我(SELECT * FROM table WHERE id > '$1' ORDER BY id DESC LIMIT 3)right 所以我 (SELECT * FROM table WHERE id < '$1' ORDER BY id DESC LIMIT 3) 其中 $1 是每组的最后一项,因此 (13 || 11 || 7) 来自 (15, 14, 13 ) || (12, 11, 10) || (9,8,7)

好吧,想象一下上面的详细解释的表示,如下所示:

<- [ 15 - 14 - 13 - 12 - 11 - 10 - 9 - 8 - 7 ] ->
   [    15     ]  [    14     ]  [    13     ]

好的,问题是当“右查询”到达最后一项:7时,结果 - set 是 (6, 5, 4) 显然是正确的,但不在 我们的 15 到 7 范围内,相反,出于我的目的,它应该不返回任何内容。我怎样才能用一个 SQL 查询来做到这一点?


只是为了方便,这里是滑块演示(右侧的最新项目,使用向右箭头,超出范围); 希望这不是一个太模糊的问题,因为我很难弄清楚如何解释这个问题。 ;)

I have built a slider using AJAX for the results, and i have a little problem as follow:

assuming a table with a set of 1 to 15 rows, but, i'm working only with the first 9 rows; in a 1st stage i (SELECT * FROM table ORDER BY id DESC LIMIT 9) and use the results to build navigation and for displaying the first group.

Then in a 2nd stage i'm querying theese 9 items, 3 each time from left so i (SELECT * FROM table WHERE id > '$1' ORDER BY id DESC LIMIT 3) or right so i (SELECT * FROM table WHERE id < '$1' ORDER BY id DESC LIMIT 3) where $1 is the last item of each group so (13 || 11 || 7) from (15, 14, 13) || (12, 11, 10) || (9, 8, 7).

Well, immagine to have a representation of above verbose explanation like below:

<- [ 15 - 14 - 13 - 12 - 11 - 10 - 9 - 8 - 7 ] ->
   [    15     ]  [    14     ]  [    13     ]

Ok, the problem is when the "right-query" reach the last item: 7, the results-set is (6, 5, 4) that obviously is correct but isn't in our range of 15 to 7, instead for my purpose it should return nothing. how i can do this with one SQL query?


just for sake here is the slider demo ( latest item to the right, using the right arrow, is out of range );
hope it is not too fuzzy question cause i had an hard time figuring out how to explain the problem. ;)

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

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

发布评论

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

评论(1

堇年纸鸢 2024-11-22 11:08:00

在第一阶段,您可以记录返回行中的最小id。然后在您的其他查询中,只需添加一个 WHERE 条件以确保所选 id 大于或等于该最小值,例如,

SELECT * FROM table WHERE id <'$1' AND id >='$min' ORDER BY id DESC LIMIT 3

在您的最小 id 为 7 并且“正确”查询使用值 7 完成的情况下,它不会返回任何内容。如果我正确理解你的问题,这就是你想要的行为。

In the 1st stage, you can record the minimum id in the returned rows. Then in your other queries, just add a WHERE condition to make sure the selected ids are greater than or equal to that minimum, for example

SELECT * FROM table WHERE id <'$1' AND id >='$min' ORDER BY id DESC LIMIT 3

in the case where your minimum id is 7 and the "right" query is done with the value 7, it will return nothing. If I understand your question correctly, this is the behavior you want.

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