简体   繁体   English

当我知道第二个行时,从SQL表中获取下一行的最简单方法

[英]Simplest way to get the next Row from an SQL table when I know the second one

Hi everyone I am trying to write a sorting script 大家好,我正在尝试编写排序脚本

For this my user will click a move up button which posts the id of the current selection we want to move up to a new page where the script is processed. 为此,我的用户将单击一个上移按钮,该按钮将发布我们要向上移动到处理脚本的新页面的当前选择的ID。

So using the fetch functions below i am getting the sort id of the current row we want to move up 因此,使用下面的获取函数,我得到了我们要向上移动的当前行的排序ID

$sqlCurrent = "SELECT * FROM `contact` WHERE `contact_id` = $id LIMIT 0, 1 ";

$resultsCurrent= mysql_query($sqlCurrent) or die(mysql_error());

$rowC = mysql_fetch_row($resultsCurrent);

$currentSort =$rowC[9];

I then pulled out all the data in decending order using 然后我使用降序拉出所有数据

Now if my current sort order is 6 I want to look for the row with the sort order with 3 or 4 or 5 in order so i used the decending order and the next sort scrip comes up in the next table. 现在,如果我当前的排序顺序为6,我想按3或4或5的顺序查找具有排序顺序的行,因此我使用了降序顺序,并且下一个排序记录已出现在下表中。

$sql = "SELECT * FROM `contact` ORDER BY `contact`.`contact_sortOrder` DESC LIMIT 0, 30 ";

The question is how do I simply get data from that row using 1 or maybe 2 functions. 问题是如何使用1个或2个函数简单地从该行获取数据。

We cant simply look for the next sort order because it is possible it wont be there. 我们不能简单地寻找下一个排序顺序,因为它可能不会在那里。

For this example i have used a database like this 对于此示例,我使用了这样的数据库

rowId 1 Sort order 6
rowId 2 Sort Order 2
rowId 3 Sort Order 4

Now I am row Id 3 and want to replace it with the next one. 现在我是第3行,并想用下一个替换它。 So i need to pick up rowId 2 somehow using the shortest method. 因此,我需要使用最短的方法以某种方式获取rowId 2。

Any help will be useful 任何帮助都会有用

Could be as simple as 可能像

$query = "
  SELECT
    x,y,z
  FROM
    contact
  WHERE
    contact_sortOrder < $currentSort
  LIMIT
    1
";

(assuming $currentSort is safe for "direct insertion" into the query. see http://docs.php.net/pdo.prepared-statements ) (假设$ currentSort对于“直接插入”查询是安全的。请参见http://docs.php.net/pdo.prepared-statements

select      prev.*
from        contact as curr
left join   contact as prev on prev.contact_sortOrder < curr.contact_sortOrder
where       curr.contact_id = $id
order by    prev.contact_sortOrder desc
limit 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM